import {
  Controller,
  UseInterceptors,
  CacheInterceptor,
  HttpService,
  Get,
  Param,
  CacheTTL,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { AxiosResponse } from 'axios';
import { map, flatMap, catchError } from 'rxjs/operators';
import { response } from 'express';
import { BuildingService } from 'src/building/building.service';
import { ConfigService } from '@nestjs/config';

@Controller('building-info')
@UseInterceptors(CacheInterceptor)
export class BuildingInfoController {
  private readonly URL: string = this.configService.get<string>('URL');
  private readonly rentCafe: string = this.configService.get<string>(
    'RENTCAFE',
  );
  //URL: string = 'http://dvora.flycommunications.com/wp-json/wp/v2/';
  // staging: string = 'https://cms.dvoralife.com/wp-json/wp/v2/';
  // rentCafe: string =
  //   'https://api.rentcafe.com/rentcafeapi.aspx?apitoken=ODU0Nzk%3d-InaOhyAR1SE%3d&requestType=';
  constructor(
    private readonly httpService: HttpService,
    private readonly buildingService: BuildingService,
    private readonly configService: ConfigService,
  ) {}

  @CacheTTL(3600)
  @Get('info/code/:id/specials')
  async getBuildSpecialsById(
    @Param('id') id: string,
  ): Promise<Observable<AxiosResponse>> {
    const promotions = await this.buildingService.getPromotions(id);
    return promotions;
  }

  @CacheTTL(3600)
  @Get('list')
  async getListOfBuildings(): Promise<Observable<AxiosResponse>> {
    const url = `${this.URL}building?_fields=id,acf,slug,featured,title,building_type,_links&_embed=building_type,wp:term`;
    const promos = await this.buildingService.getPromotions();
    const buildings = this.httpService.get(url).pipe(
      map(response => {
        const building = response.data.map(val => {
          const { id, acf, slug, title, building_type, featured } = val;

          const types = val._embedded['wp:term'][1]
            .filter(rs => building_type.indexOf(rs.id) > -1)
            .map(e => {
              return { name: e.name, id: e.id };
            });

          const featuredTag = val._embedded['wp:term'][3]
            .filter(ft => featured.indexOf(ft.id) > -1)
            .map(f => f.name);

          const promo = promos.filter(evt => evt.id === acf.id);
          let build = { ...val, types: types, featured: featuredTag };

          if (promo) build = { ...build, promo: { ...promo[0] } };
          return build;
        });
        return building;
      }),
    );
    return buildings;
  }
  getids(url) {
    const x = this.httpService.get(url).pipe(
      map(response => {
        const ids = response.data
          .filter(evt => !evt.Error)
          .map(evt => {
            return {
              id: evt.id,
              title: evt.title.rendered.toLowerCase(),
              voygaer: evt.acf.id,
              slug: evt.slug,
              position: {
                longitude: evt.acf.longitude,
                latitude: evt.acf.latitude,
              },
              city: {
                name: evt.acf.city,
                id: evt.city,
              },
            };
          });
        return ids;
      }),
    );
    return x;
  }

  @CacheTTL(3600)
  @Get('list/code/:id')
  getCodes(@Param('id') id: string): Observable<AxiosResponse> {
    const url = ` ${this.rentCafe}property&voyagerPropertyCode=${id}`;
    const building = this.httpService
      .get(url)
      .pipe(map(response => response.data));
    return building;
  }

  @CacheTTL(3600)
  @Get('list/id')
  getListOfBuildingIds(): Observable<AxiosResponse> {
    const url = `${this.URL}building?_fields=id,slug,title,building_type,city,acf,featured`;

    const buildingIds = this.getids(url);

    return buildingIds;
  }

  @CacheTTL(3600)
  @Get('list/id/:city')
  getListOfBuildingIdsWithCity(
    @Param('city') city?: string,
  ): Observable<AxiosResponse> {
    let url = `${this.URL}building?_fields=id,slug,title,building_type,city,acf,featured`;
    if (city) {
      url = `${url}&city=${city}`;
    }
    const buildingIds = this.getids(url);

    return buildingIds;
  }

  @CacheTTL(3600)
  @Get('info/:slug')
  getBuildingInfoBySlug(
    @Param('slug') slug: string,
  ): Observable<AxiosResponse> {
    const url = `${this.URL}building?slug=${slug}&_fields=id,title,acf,amenities`;
    const building = this.httpService
      .get(url)
      .pipe(map(response => response.data));
    return building;
  }

  @CacheTTL(3600)
  @Get('amenities')
  getAmenitiesMap(): Observable<AxiosResponse> {
    const url = `${this.URL}amenities?per_page=100&_fields=id,slug,acf`;
    const amenities = this.httpService.get(url).pipe(
      map(response => {
        const t = response.data.map(evt => {
          return {
            id: evt.id,
            name: evt.acf.name,
            icon: evt.acf.icon,
            slug: evt.slug,
          };
        });
        return t;
      }),
    );
    return amenities;
  }

  @CacheTTL(3600)
  @Get('flooplanImages/:propertyId')
  getFloorplanImage(
    @Param('propertyId') propertyId: string,
  ): Observable<AxiosResponse> {
    const url = `${this.rentCafe}floorplan&propertyId=${propertyId}`;
    const floorplans = this.httpService
      .get(url)
      .pipe(map(response => response.data));
    return floorplans;
  }

  formatString(info) {}
}
