import { Bindings, initializeBindings } from "@coveo/atomic";
import { Component, Element, Prop } from "@stencil/core";
import { waitForAtomic } from "../../utils/atomic";
import { buildContext } from "@coveo/headless";

@Component({
  tag: "recs-initialization-helper",
  shadow: true,
})
export class RecsInitializationHelper {
  @Prop() userCountry!: string;
  private bindings?: Bindings;
  @Element() private host!: Element;

  public async connectedCallback() {
    try {
      await waitForAtomic();
      this.bindings = await initializeBindings(this.host);
      let toDate = new Date().toISOString();
      let fromDate = new Date();
      if(fromDate.getMonth() == 1) {
        fromDate.setMonth(12);
        fromDate.setFullYear(fromDate.getFullYear() - 1);
      }
      else {
        fromDate.setMonth(fromDate.getMonth() - 1);
      }
      let filter = encodeURIComponent(`(clicks.c_context_user_country_snow=='${this.userCountry}')`);

      let url = `https://${this.bindings?.engine.state.configuration.organizationId}.admin.org.coveo.com/rest/ua/v15/stats/combinedData?from=${fromDate.toISOString()}&to=${toDate}&m=DocumentView&d=documentTitle&d=documentURL&d=clicks.c_context_user_country_snow&d=documentSysUriHash&f=${filter}&p=1&n=10&s=DocumentView&asc=false&includeMetadata=true`;
      const reqHeaders = new Headers();
      reqHeaders.append("authorization", "Bearer xxf42da36f-db11-4565-8358-8bac8c307236");

      const requestOptions = {
        method: "GET",
        headers: reqHeaders
      };

      let response:any = await fetch(url, requestOptions);
      response = await response.json();
      debugger;
      if(response.combinations.length>0) {
        let dqExp = response.combinations.map((c:any) => c.documentSysUriHash);
        buildContext(this.bindings.engine).add("dqExp", dqExp);
        (this.bindings.interfaceElement as any).getRecommendations();
      }
      else {
        this.bindings.interfaceElement.style.display = "none";
      }
    } catch (error) {
      console.error(error);
    }
  } 
}
