import { Controller, Get, Response, HttpService } from '@nestjs/common';
import { SitemapStream, streamToPromise } from 'sitemap';
import { map, flatMap, catchError } from 'rxjs/operators';
import { AxiosResponse } from 'axios';
import { ConfigService } from '@nestjs/config';
@Controller()
export class SitemapController {
  private readonly URL: string = this.configService.get<string>('URL');

  // URL: string = 'http://dvora.flycommunications.com/wp-json/wp/v2/';
  // url: string = 'https://cms.dvoralife.com/wp-json/wp/v2/';
  private readonly acf: string = this.URL.replace('/wp/v2/', '/acf/v3/');
  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {}

  getHomeHero(): Promise<AxiosResponse> {
    const url = `${this.URL}dvora_home_page/?_fields=acf`;
    const units = this.httpService
      .get(url)
      .pipe(map(response => response.data));
    return units.toPromise();
  }
  getBuildings(): Promise<AxiosResponse[]> {
    const url = `${this.URL}building/?_fields=id,slug`;
    const units = this.httpService
      .get(url)
      .pipe(map(response => response.data));
    return units.toPromise();
  }

  getBuildingHero(id): Promise<AxiosResponse> {
    const url = `${this.acf}building/${id}/gallery_block`;
    const building = this.httpService
      .get(url)
      .pipe(map(response => response.data));
    return building.toPromise();
  }

  @Get('sitemap')
  async sitemap(@Response() res) {
    const test = await this.getBuildings();
    const buildingsList = await this.getBuildings();
    res.set('Content-Type', 'text/xml');
    const smStream = new SitemapStream({
      hostname: 'https://example.com',
    });

    for (let i = 0; i < buildingsList.length; i++) {
      const t = await this.getBuildingHero(buildingsList[i]['id']);
      const image = t['gallery_block'][0]['image_gallery'][0];
      smStream.write({
        url: `/buildings/${buildingsList[i]['slug']}`,
        img: image,
        changefreq: 'monthly',
      });
    }

    smStream.write({
      url: '/page-1/',
      changefreq: 'daily',
      priority: 0.3,
    });
    smStream.write({
      url: '/page-2/',
      changefreq: 'monthly',
      priority: 0.7,
    });
    smStream.write({
      url: '/page-3/',
    });
    smStream.write({
      url: '/page-4/',
      img: 'http://urlTest.com',
    });
    smStream.end();
    streamToPromise(smStream).then(xml => {
      res.send(xml);
    });
  }
}
