'use strict';

import fetch from 'node-fetch';
import moment from 'moment';
import constants from '../constants'
import { relation } from '../helpers'

// -- Internal
const API = `http://query.yahooapis.com/v1/public/yql?q=`
const RELATIONS = ['when', 'location'];

export default (state) => {

  return new Promise((resolve, reject) => {
    const { location, when } = relation(RELATIONS, state.nlp.relations);
    const ms = new Date()
    const query = escape(`select item from weather.forecast where woeid in (select woeid from geo.places where text='${location}') and u='c' | truncate(count=1)`);
    console.log('ActionForecastYahoo'.bold.yellow, `location: ${location}, when: ${when}`);

    fetch(`${API}${query}&format=json`)
      .then(response => response.text())
      .then(body => {
        const item = JSON.parse(body).query.results.channel.item;

        state.actions.push({
          ms: (new Date() - ms),
          engine: 'yahoo',

          type: constants.action.type.rich,
          title: item.title,
          url: item.link.split('*')[1],
          value: {
            code: item.condition.code,
            condition: item.condition.text,
            temperature: item.condition.temp,
          },
          date: item.condition.date,
          // extra: item.forecast
        });

        resolve(state);
      }).catch(function(error) {
        reject(error);
      });
  });
};

@@ -856,16 +856,98 @@
 el.item;
+%0A        const condition = _extractCondition(item.condition, item.forecast, when);
 %0A%0A      
@@ -1029,17 +1029,16 @@
 yahoo',%0A
-%0A
         
@@ -1156,84 +1156,293 @@
     
-value: %7B%0A            code: item.condition.code,%0A            condition: item.
+condition,%0A          // extra: item.forecast,%0A        %7D);%0A%0A        resolve(state);%0A      %7D).catch(function(error) %7B%0A        reject(error);%0A      %7D);%0A  %7D);%0A%7D;%0A%0Aconst _extractCondition = (condition = %7B%7D, forecast = %5B%5D, when) =%3E %7B%0A  let value = %7B%0A    code: condition.code,%0A    condition: 
 cond
@@ -1453,24 +1453,16 @@
 n.text,%0A
-        
     temp
@@ -1470,21 +1470,16 @@
 rature: 
-item.
 conditio
@@ -1494,195 +1494,417 @@
     
-      %7D,%0A          date: item.condition.date,%0A          // extra: item.forecast%0A        %7D);%0A%0A        resolve(state);%0A      %7D).catch(function(error) %7B%0A        reject(error)
+date: moment(condition.date, 'ddd, DD MMM YYYY hh:mm A ZZ').format(),%0A  %7D;%0A%0A  forecast.map( (condition) =%3E %7B%0A    const date = moment(condition.date, 'DD MMM YYYY');%0A%0A    if (date.isSame(when, 'day')) %7B%0A      return value = %7B%0A        code: condition.code,%0A        condition: condition.text,%0A        temperature: %5Bcondition.low, condition.high%5D,%0A        date: date.format(),%0A      %7D
 ;%0A    
+%7D%0A
   %7D);%0A
+%0A
   
-%7D)
+return value
 ;%0A%7D;

Action ForecastYahoo extract the condition for a determinate {when} relation