// var params = null;
class SalesDetail {
  constructor(params) {
    console.log("in SalesDetail Class")
    this.params = params;
    this.rowData = params.data.data;
    if (params.context.newRecords) {
      let continent = this.params.data.continent
      this.rowData = this.rowData.concat(
        params.context.newRecords[continent]
      );
    }
  }

  eGui() {
    var eTemp = document.createElement('div');
    eTemp.innerHTML = this.getTemplate();
    this.eGui = eTemp.firstElementChild;

    this.setupDetailGrid();
    return this.eGui;
  }

  setupDetailGrid() {
    var eDetailGrid = this.eGui.querySelector('.full-width-grid');
    var detailGridOptions = {
      columnDefs: [
        { field: 'country', rowGroup: true },
        { field: 'sales', aggFunc: 'sum' },
        { field: 'cost' },
        { field: 'product', pivot: true },
      ],
      defaultColDef: {
        flex: 1,
        minWidth: 150,
      },
      pivotMode: true,
      rowData: this.rowData,
    };

    new agGrid.Grid(eDetailGrid, detailGridOptions);

    this.detailGridApi = detailGridOptions.api;

    var masterGridApi = this.params.api;
    var rowId = this.params.node.id;

    var gridInfo = {
      id: rowId,
      api: detailGridOptions.api,
      columnApi: detailGridOptions.columnApi,
    };
    masterGridApi.addDetailGridInfo(rowId, gridInfo);
  }

  getTemplate() {
    var template = `<div class="full-width-panel">
      <div class="full-width-details"></div>
      <div class="full-width-grid ag-theme-alpine"></div>
    </div>`;

    return template;
  }
}

class DetailCellRenderer {
  init(params) {
    console.log("in DetailCellRenderer Class")
    this.params = params;
    var colId = params.context.selectedDetail;
    // console.log(params)

    if (colId === "cost") {
      var costDetail = new CostDetail(params);
      this.eGui = costDetail.eGui();
    } else if (colId === "orders") {
      var ordersFormDetail = new OrdersFormDetail(params);
      this.eGui = ordersFormDetail.eGui();
    } else if (colId === "sales") {
      var salesDetail = new SalesDetail(params);
      this.eGui = salesDetail.eGui();
    }
  }
  getGui() {
    return this.eGui;
  }
}

class CostDetail {
  constructor(params) {
    console.log("in CostDetail Class")
    this.params = params;
  }

  eGui() {
    return this.createChart();
  }

  createChart() {
    let continent = this.params.data.continent;
    let rowData = this.params.data.data;
    let newRecords = this.params.context.newRecords;
    let productACost = 0;
    let productBCost = 0;
    let productCCost = 0;

    if (newRecords) {
      rowData = rowData.concat(newRecords[continent]);
    }

    rowData.map(row => {
      switch (row.product) {
        case "A":
          productACost += row.cost;
          break;
        case "B":
          productBCost += row.cost;
          break;
        case "C":
          productCCost += row.cost;
          break;
      }
      return;
    });

    let container = document.createElement("div");
    container.style.height = "310px"
    var options = {
      container: container,
      autoSize: true,
      title: {
        text: `(${continent}) Costs by Product`,
        fontSize: 18
      },
      series: [
        {
          data: [
            {
              product: "Product A",
              cost: productACost
            },
            {
              product: "Product B",
              cost: productBCost
            },
            {
              product: "Product C",
              cost: productCCost
            }
          ],
          type: "pie",
          labelKey: "product",
          angleKey: "cost",
          label: {
            minAngle: 0
          },
          callout: {
            strokeWidth: 1,
            length: 5
          }
        }
      ],
      legend: {
        enabled: false
      }
    };

    var chart = agCharts.AgChart.create(options);
    return container;
  }
}


const treeOpen = 'https://raw.githubusercontent.com/LouisMoore-agGrid/js-ag-grid-52eyso/50413f659cdfbe903ec14d9a5d4b7cf175b76637/tree-open.svg';
const treeClosed = 'https://raw.githubusercontent.com/LouisMoore-agGrid/js-ag-grid-52eyso/aacef9f45dae7ea5822c4b76bf1c981a74451435/tree-closed.svg';

var columnDefs = [
    { field: 'continent' },
    {
        field: 'sales',
        cellRenderer: (params) => makeMasterCellRenderer(params, 'sales'),
    },
    {
        field: 'cost',
        cellRenderer: (params) => makeMasterCellRenderer(params, 'cost'),
    },
    {
        field: 'orders',
        cellRenderer: (params) => makeMasterCellRenderer(params, 'orders'),
    },
];

const gridOptions = {
    columnDefs: columnDefs,
    detailRowAutoHeight: true,
    rowData: rowData, 
    masterDetail: true,
    detailCellRenderer: 'myDetailCellRenderer',
    components: {
        myDetailCellRenderer: DetailCellRenderer, 
    },
};

function makeMasterCellRenderer(params, col) {
    console.log("in makeMasterCellRenderer")
    let isExpanded = params.node.expanded;
    let container = document.createElement('div');
    let chevron = document.createElement('img');
    let span = document.createElement('span');
    let openCol = null;

    chevron.classList.add(`row-${params.node.data.id}`);
    chevron.classList.add('pointer-class');
    container.classList.add('master-container');

    console.log("params.context", params.context)
    if (params.context) {
      openCol = params.context.chevKeyMap[chevron.className];
    }
    let chevronState = isExpanded && col === openCol ? treeOpen : treeClosed;
    chevron.setAttribute('src', chevronState);

    switch (col) {
        case 'orders':
            span.innerText = 'Orders Form';
            container.appendChild(chevron);
            break;
        default:
            span.innerText = params.value;
            container.appendChild(chevron);
            break;
    }

    chevron.addEventListener('click', (event) => {
        console.log("OPening")
        let chevron = event.target;
        openDetail(params, col, chevron);
    });

    container.appendChild(span);
    return container;
}

const openDetail = (params, column, cellRenderer) => {
  console.log("==>>",gridOptions.context.chevKeyMap[cellRenderer.className])
  if (
        gridOptions.context &&
        gridOptions.context.chevKeyMap[cellRenderer.className] === column &&
        params.node.expanded
    ) {
        console.log("==>>",gridOptions.context.chevKeyMap[cellRenderer.className])
        params.node.setExpanded(false);
        cellRenderer.setAttribute('src', treeClosed);
        return;
    }
    //  gridApi.setGridOption("context", { reportingCurrency: value });
    gridOptions.context = { ...gridOptions.context, selectedDetail: column };
    // console.log(gridOptions)
    // gridApi.setGridOption("context", { selectedDetail: column });
    let className = '';
    cellRenderer.classList.forEach((cssClass) => {
        if (cssClass.indexOf('row') !== -1) {
            className = cssClass;
        }
    });
    let nodeRenderers = document.querySelectorAll(`.${className}`);
    nodeRenderers.forEach((renderer) => {
        renderer.setAttribute('src', treeClosed);
    });
    params.node.setExpanded(true);
    if (gridOptions.context.chevKeyMap) {
        gridOptions.context.chevKeyMap[cellRenderer.className] = column;
    } else {
        gridOptions.context.chevKeyMap = {};
        gridOptions.context.chevKeyMap[cellRenderer.className] = column;
    }
    cellRenderer.setAttribute('src', treeOpen);

    if (params.node.detailNode) {
        params.api.redrawRows({ rowNodes: [params.node.detailNode] });
    }
};

// new agGrid.Grid(document.querySelector('#myGrid'), gridOptions);
// Initialize the grid using the new createGrid method
const gridApi = agGrid.createGrid(document.querySelector('#myGrid'), gridOptions);

// You can now use gridApi for further API calls
// console.log(gridApi); // Example: logs the grid API object

