import { number } from 'yup';
import GraphQLService from './GraphQLService';

export interface FloorplanData{
  id: number 
  title : string
  short_desc : string
  number : string
  bed : number
  bath : number
  sqft : number
  garage : number
  garage_type:number|string
  dimensions : string
  front_porch : string
  back_porch : string
  fr_floor_plan_roomtypes?: Array<{
    id: string | string[];
    fr_roomtype: any;   
  }>;
  fr_floor_plan_features?: Array<{
    id: string | string[];
    fr_feature: any;   
  }>;
  fr_floor_plan_architecture_styles?: Array<{
    id?: string | string[];
    fr_floor_plan_architecture_styles: any; 
    fr_architecture_style:any  
  }>;
  fr_floor_plan_attachments?:Array<{
    id?: string | string[] | number | any;
    file_attachment_url:any
    cover:string
    fr_floor_plan:any
  }>;
  
}

export interface FloorplanData2 extends FloorplanData {
  file_pdf?: string;
  file_pdf_url?: {
    direct: string;
    thumb: string;
  };
}



export interface FloorplanInData{
  title : string
  short_desc : string
  number : string
  bed : number
  bath : number
  sqft : number
  garage : number
  garage_type:number|string
  dimensions : string
  front_porch : string
  back_porch : string
}
export interface FloorplanOPData {
  FloorPlanFind?: {
      rows?:FloorplanData2[]      
      total : number
      pages : number
      id?:string 
  };
}


export interface FloorplanIdOPData {
  FloorPlanFindOneById?:FloorplanData2
}
export interface FloorplanCreateOPData {
  FloorPlanCreate?:FloorplanData[]
}
interface SnapshotData {
  message : string
  result : string
  imp : string
  mismatch : string
  notFound : string
  conflict : string
  success : string
  error : string
  alert : string
  warning : string
  notice : string
  info : string
}
export interface FloorplanUpdateOPData {
  FloorPlanUpdate?:{
    snapshot: SnapshotData
    affected : number
    affectedRows ?: FloorplanData
  }
}
export interface FloorplanUpsertOPData {
  FloorplanUpsert?:FloorplanData
}
export interface FloorplanDeleteOPData {
  FloorPlanDelete?:{
    snapshot: SnapshotData
    affected : number
  }
}

export interface Filters {
  floorPlan:string;
  sqftMin: string;
  sqftMax: string;
  beds: string[];
  baths: string[];
  garage: string[];
  garage_type:string[]
  rooms: string[];
  features: string[];
  architectureStyles: string[];
  pageSize : number;
  start : number;
  field : string;
  sort : string;
};

function buildFilterFromCriteria(Filters: Filters): any {
  console.log(Filters);
  
  const order = Filters.field ? {
    [Filters.field]: Filters.sort 
  } : {
    "id": "desc" 
  };

  const filter: any = {
    order: order,
    skip: Filters.start,
    take: Filters.pageSize
  };

  const queryObject: any = {};

  queryObject["fr_floor_plan_attachments"] = [{ "cover":null /* { "nulls": false } */ }];
  if (Filters.floorPlan && Number(Filters.floorPlan)) {
    queryObject["number"] = { "equal": `${Filters.floorPlan}`};
  }

  if (Filters.floorPlan && !Number(Filters.floorPlan)) {
    queryObject["title"] = { "like": `%${Filters.floorPlan}%`};
  }

  if (Filters.sqftMin && Filters.sqftMax) {
    queryObject["sqft"] = { "between": [Filters.sqftMin, Filters.sqftMax] };
  }
  else if(Filters.sqftMin){
    queryObject["sqft"] = { "mte": Filters.sqftMin };
  }
  else if (Filters.sqftMax) {
    queryObject["sqft"] = { "lte": Filters.sqftMax };
  }

  if (Filters.garage && Filters.garage.length > 0) {
    queryObject["garage"] = { "into": Filters.garage };
  }
  if (Filters.garage_type && Filters.garage_type.length > 0) {
    queryObject["garage_type"] = { "into": Filters.garage_type };
  }

  if (Filters.rooms && Filters.rooms.length > 0) {
    queryObject["fr_floor_plan_roomtypes"] = { "roomtype_id": { "into": Filters.rooms } };
  }

  if (Filters.features && Filters.features.length > 0) {
    queryObject["fr_floor_plan_features"] = { "feature_id": { "into": Filters.features } };
  }

  if (Filters.architectureStyles && Filters.architectureStyles.length > 0) {
    queryObject["fr_floor_plan_architecture_styles"] = { "archstyle_id": { "into": Filters.architectureStyles } };
  }
  
  if (Filters.beds && Filters.beds.length > 0) {
    const greaterThanBeds = Filters.beds.filter(bed => bed.includes(">"));
    const exactBeds = Filters.beds.filter(bed => !bed.includes(">"));

    if (exactBeds.length > 0 && greaterThanBeds.length > 0) {
      const greaterThanValue = greaterThanBeds[0].replace(">", "").trim();
      
      queryObject['bed'] = {
        "into": exactBeds,  
        "mte": greaterThanValue
      };
    }
    else if(exactBeds.length > 0){
      queryObject['bed'] = { "into": exactBeds};
    }
    else if (greaterThanBeds.length > 0) {
      const greaterThanValue = greaterThanBeds[0].replace(">", "").trim();
      queryObject['bed'] = { "mte": greaterThanValue};
    }
  }

  if (Filters.baths && Filters.baths.length > 0) {
    const greaterThanBaths = Filters.baths.filter(bath => bath.includes(">"));
    const exactBaths = Filters.baths.filter(bath => !bath.includes(">"));
    if (exactBaths.length > 0 && greaterThanBaths.length > 0) {
      const greaterThanValue = greaterThanBaths[0].replace(">", "").trim();
      queryObject['bath'] = {
        "into": exactBaths,  
        "mte": greaterThanValue
      };
    }
    else if(exactBaths.length > 0){
      queryObject['bath'] = { "into": exactBaths};
    }
    else if (greaterThanBaths.length > 0) {
      const greaterThanValue = greaterThanBaths[0].replace(">", "").trim();
      queryObject['bath'] = { "mte": greaterThanValue};
    }
  }

  if (Object.keys(queryObject).length > 0) {
    filter["where"] = queryObject;
  }
  
  return filter;
}

class FloorPlanService extends GraphQLService {
    constructor() {
      super();
    }

    getFloorplan(pageSize:number, start:number, quickSearch:any,sortorder:string,sortField:string):Promise<FloorplanOPData |null | undefined>{
      const filter: any = {
        "order": {
          [sortField]: sortorder,
        },
        "skip": start,
        "take": pageSize
      };

      const queryObject: any = {};

      if (Number(quickSearch)) {
        queryObject["number"] = { "equal": `${quickSearch}`};
      } else {
        queryObject["title"] = { "like": `%${quickSearch}%`};
      } 

     /*  if (quickSearch) {
        queryObject["title"] = { "like": `%${quickSearch}%`};
      } */


      if (Object.keys(queryObject).length > 0) {
        filter["where"] = queryObject;
      }

      const Query =`query Rows($filter: FloorPlanFindInput!) {
                    FloorPlanFind(filter: $filter) {
                      rows {
                        id
                        title
                        short_desc
                        number
                        bed
                        bath
                        sqft
                        garage
                        garage_type
                        dimensions
                        front_porch
                        back_porch
                        file_pdf
                        fr_floor_plan_roomtypes {
                          id
                          roomtype_id
                          fr_roomtype {
                            id
                            title
                          }
                        }
                        fr_floor_plan_features {
                          id
                          feature_id
                          fr_feature {
                            id
                            title
                          }
                        }
                        fr_floor_plan_attachments {
                          id
                          floorplan_id
                          file_attachment_url {
                            thumb
                            secure
                            direct
                          }
                          file_attachment
                        }
                        fr_floor_plan_architecture_styles {
                          id
                          archstyle_id
                          fr_architecture_style {
                            id
                            title
                          }
                        }
                        file_pdf_url {
                          direct
                          secure
                          thumb
                        }
                      }
                      total
                      pages
                    }
                  }`;
                  const variables = {filter};
  
      return this.execute(Query, variables); 
    }

    getFloorplanById(Id: number):Promise<FloorplanIdOPData |null | undefined>{
      const Query =`query FloorPlanFindOneById($input: FloorPlanFindOneByIdInput!) {
                    FloorPlanFindOneById(input: $input) {
                      id
                      title
                      short_desc
                      number
                      bed
                      bath
                      sqft
                      garage
                      garage_type
                      dimensions
                      front_porch
                      back_porch
                      fr_floor_plan_features {
                        id
                        feature_id
                        fr_feature {
                          id
                          title
                        }
                      }
                      fr_floor_plan_attachments {
                        id
                        file_attachment
                        file_attachment_url {
                          direct
                          secure
                          thumb
                        }
                        fr_floor_plan {
                          title
                            number
                        }
                        floorplan_id
                        cover
                      }
                      fr_floor_plan_architecture_styles {
                        id
                        fr_architecture_style {
                          id
                          title
                        }
                      }
                      fr_floor_plan_roomtypes {
                        id
                        roomtype_id
                        fr_roomtype {
                          id
                          title
                        }
                      }
                      file_pdf_url {
                        thumb
                        secure
                        direct
                      }
                      file_pdf
                    }
                  }`;
            const variables = {
                  "input": {
                    "id": Id
                  }
              };
  
      return this.execute(Query, variables); 
    }

    createFloorplan(FloorplanINData: FloorplanInData):Promise<FloorplanCreateOPData |null | undefined>{
      const Query =`mutation FloorPlanCreate($input: [FloorPlanCreateInput!]!) {
                    FloorPlanCreate(input: $input) {
                      id
                      title
                      short_desc
                      number
                      bed
                      bath
                      sqft
                      garage
                      garage_type
                      dimensions
                      front_porch
                      back_porch
                    }
                  }`;
      const variables = {
        input:[FloorplanINData]
      };
  
      return this.mutate<FloorplanCreateOPData>(Query, variables); 
    }

    updateFloorplan(FloorplanINData: FloorplanData):Promise<FloorplanUpdateOPData |null | undefined>{
      const Query =`mutation FloorPlanUpdate($input: FloorPlanUpdateInput!) {
                    FloorPlanUpdate(input: $input) {
                      snapshot {
                        message
                        result
                        imp
                        mismatch
                        notFound
                        conflict
                        success
                        error
                        alert
                        warning
                        notice
                        info
                      }
                      affected
                      affectedRows {
                        id
                        title
                        short_desc
                        number
                        bed
                        bath
                        sqft
                        garage
                        garage_type
                        dimensions
                        front_porch
                        back_porch
                      }
                    }
                  }`;
                  
            const variables = {
              "input": {
                "sets": {
                  "back_porch": `${FloorplanINData.back_porch}`,
                  "bath": FloorplanINData.bath,
                  "bed": FloorplanINData.bed,
                  "dimensions": `${FloorplanINData.dimensions}`,
                  "front_porch": `${FloorplanINData.front_porch}`,
                  "garage": FloorplanINData.garage,
                  "garage_type":FloorplanINData.garage_type,
                  "number": `${FloorplanINData.number}`,
                  "short_desc": `${FloorplanINData.short_desc}`,
                  "sqft": FloorplanINData.sqft,
                  "title": `${FloorplanINData.title}`,
                },
                "where": [
                  {
                    "id": {
                      "equal":  `${FloorplanINData.id}`
                    }
                  }
                ]
              }
            };
  
      return this.mutate<FloorplanUpdateOPData>(Query, variables); 
    }

    upsertFloorplan(FloorplanINData: FloorplanData):Promise<FloorplanUpsertOPData |null | undefined>{
      const Query =`mutation FloorPlanUpsert($input: [FloorPlanUpsertInput!]!) {
                    FloorPlanUpsert(input: $input) {
                      id
                      title
                      short_desc
                      number
                      bed
                      bath
                      sqft
                      garage
                      garage_type
                      dimensions
                      front_porch
                      back_porch
                    }
                }`;
            const variables = {
              input:[FloorplanINData]
            };
  
      return this.mutate<FloorplanUpsertOPData>(Query, variables); 
    }

    deleteFloorplan(Id: number):Promise<FloorplanDeleteOPData |null | undefined>{
      const Query =`mutation FloorPlanDelete($input: FloorPlanDeleteInput!) {
                    FloorPlanDelete(input: $input) {
                      snapshot {
                        message
                        result
                        imp
                        mismatch
                        notFound
                        conflict
                        success
                        error
                        alert
                        warning
                        notice
                        info
                      }
                      affected
                    }
                  }`;
            const variables = {
              input:{
                "where": [
                  {
                    "id": {
                      "equal": `${Id}`
                    }
                  }
                ]
              }
            };
  
      return this.mutate<FloorplanDeleteOPData>(Query, variables); 
    }

    getFloorplanByTitle(ID:string):Promise<FloorplanOPData |null | undefined>{
      const Query =`query Rows($filter: FloorPlanFindInput!) {
                    FloorPlanFind(filter: $filter) {
                      rows {
                        id
                        title
                        short_desc
                        number
                        bed
                        bath
                        sqft
                        garage
                        garage_type
                        dimensions
                        front_porch
                        back_porch
                        fr_floor_plan_roomtypes {
                          id
                          roomtype_id
                          fr_roomtype {
                            id
                            title
                          }
                        }
                        fr_floor_plan_features {
                          id
                          feature_id
                          fr_feature {
                            id
                            title
                          }
                        }
                        fr_floor_plan_attachments {
                          id
                          floorplan_id
                          file_attachment_url {
                            thumb
                            secure
                            direct
                          }
                          file_attachment
                        }
                        fr_floor_plan_architecture_styles {
                          id
                          archstyle_id
                          fr_architecture_style {
                            id
                            title
                          }
                        }
                        file_pdf
                        file_pdf_url {
                          direct
                          thumb
                        }
                      }
                      total
                      pages
                    }
                  }`;
      const variables = {
          "filter": {
            "where": [
              {
                "id": {
                  "equal": ID
                }
              }
            ]
          }
      };
  
      return this.execute(Query, variables); 
    }

    sortAscGetFloorplan(sortOrder:string,pageSize:number, start:number):Promise<FloorplanOPData |null | undefined>{
      const Query =`query Rows($filter: FloorPlanFindInput!) {
        FloorPlanFind(filter: $filter) {
          rows {
            id
            title
            short_desc
            number
            bed
            bath
            sqft
            garage
            garage_type
            dimensions
            front_porch
            back_porch
            fr_floor_plan_roomtypes {
              id
              roomtype_id
              fr_roomtype {
                id
                title
              }
            }
            fr_floor_plan_features {
              id
              feature_id
              fr_feature {
                id
                title
              }
            }
            fr_floor_plan_attachments {
              id
              floorplan_id
              file_attachment_url {
                thumb
                secure
                direct
              }
              file_attachment
            }
            fr_floor_plan_architecture_styles {
              id
              archstyle_id
              fr_architecture_style {
                id
                title
              }
            }
          }
          total
          pages
        }
      }`;
      const variables = {
        "filter": {
          "order": {
            "title": sortOrder
          },
          "skip": start,
          "take": pageSize
        }
    };

      return this.execute(Query, variables); 
    }

    getFloorplanAttachment(Id:number | string):Promise<FloorplanOPData |null | undefined>{
      const Query =`query Rows($filter: FloorPlanFindInput!) {
                    FloorPlanFind(filter: $filter) {
                      rows {
                        id
                        title
                        short_desc
                        number
                        bed
                        bath
                        sqft
                        garage
                        garage_type
                        dimensions
                        front_porch
                        back_porch
                        fr_floor_plan_roomtypes {
                          id
                          roomtype_id
                          fr_roomtype {
                            id
                            title
                          }
                        }
                        fr_floor_plan_features {
                          id
                          feature_id
                          fr_feature {
                            id
                            title
                          }
                        }
                        fr_floor_plan_attachments {
                          id
                          floorplan_id
                          file_attachment_url {
                            thumb
                            secure
                            direct
                          }
                          file_attachment
                          fr_floor_plan {
                            title
                             number
                          }
                          cover
                        }
                        fr_floor_plan_architecture_styles {
                          id
                          archstyle_id
                          fr_architecture_style {
                            id
                            title
                          }
                        }
                      }
                      total
                      pages
                    }
                  }`;
      const variables = {
          "filter": {
            "order": {
              "id": "DESC"
            },
            "where": [
              {
                "id": {
                  "equal": `${Id}`
                }
              }
            ]
          }
      };
  
      return this.execute(Query, variables); 
    } 

    getFloorplanWithFilter(Filters:Filters):Promise<FloorplanOPData |null | undefined>{


      const filter = buildFilterFromCriteria(Filters);
      const Query =`query Rows($filter: FloorPlanFindInput!) {
                    FloorPlanFind(filter: $filter) {
                      rows {
                        id
                        title
                        short_desc
                        number
                        bed
                        bath
                        sqft
                        garage
                        dimensions
                        front_porch
                        back_porch
                        garage_type
                        fr_floor_plan_roomtypes {
                          id
                          roomtype_id
                          fr_roomtype {
                            id
                            title
                          }
                        }
                        fr_floor_plan_features {
                          id
                          feature_id
                          fr_feature {
                            id
                            title
                          }
                        }
                        fr_floor_plan_attachments {
                          id
                          floorplan_id
                          file_attachment_url {
                            thumb
                            secure
                            direct
                          }
                          file_attachment
                          cover
                        }
                        fr_floor_plan_architecture_styles {
                          id
                          archstyle_id
                          fr_architecture_style {
                            id
                            title
                          }
                        }
                      }
                      total
                      pages
                    }
                  }`;

                  const variables = {filter};
  
      return this.execute(Query, variables); 
    }
}

const floorPlanServiceInstance = new FloorPlanService();
export default floorPlanServiceInstance;