<commit_before>'use strict';
var config = require('../../configs');

var http = require('http');

/**
 *The AlexaSkill Module that has the AlexaSkill prototype and helper functions
 */

var apiKey=config.getAPIKey();
var i=0,j=0;
/**
 * This function will return the train status as a string.
 * Sample output : Train departed from KARUKKUTTY(KUC) and late by 24 minutes.
 */
exports.getJsonLiveStatus= function (train_no,doj,eventCallback){

    var url =config.getBaseUrl()+"live/train/"+train_no+"/doj/"+doj+"/apikey/"+apiKey+"/";
    var state="";
    var status= "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var status=stringResult.position;
            if(stringResult.response_code!='200')
                    status="There was an error processing your request.";
            var result={speech:status,status:stringResult.position,heading:'Train Number: '+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";

        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
   return status;
}

/**
 * This function will return the stations in a route as a string.
 * Sample output : KANYAKUMARI,Source,14:10,1,  NAGARCOIL JN,14:30,14:35,1,  KULITTHURAI,15:14,15:15,1,  TRIVANDRUM CNTL,15:55,16:00,1,  KOLLAM JN,17:00,17:05,1,  KAYANKULAM,17:34,17:36,1 (Station     **name,Arriavl time,Departure time,Day of arrival.)
 */
exports.getJsonTrainRoute=function (train_no,eventCallback){

    var url =config.getBaseUrl()+'route/train/'+train_no+'/apikey/'+ apiKey+'/';
       var station_string="";
    var state = "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var station_names=[];
            var station_arrival=[];
            var station_dep=[];
            var day=[];
            for (i=0; i<stringResult.route.length; i++){
                station_names[i]=stringResult.route[i].fullname;
                station_arrival[i]=stringResult.route[i].scharr;
                station_dep[i]=stringResult.route[i].schdep;
                day[i]=stringResult.route[i].day;
                }
             var m=0;
             var update=Math.ceil(((stringResult.route.length-2)/5));
             var source_=station_names[0];
             var dest_=station_names[i-1];

             station_string=station_string+"The train starts from "+source_+" at "+station_dep[0]+" and arrives  "+dest_+" at "+station_arrival[i-1]+" on day "+day[i-1]+" passing through ";
            for (j=0; j<i-1; j=j+update){
               m=j+1;
              if((j+update)<(i-1))
                 station_string=station_string+station_names[j]+",";
                else
                 station_string=station_string+" and "+station_names[j]+".";
               }
               if(stringResult.response_code!='200')
                    station_string="There was an error processing your request.";
            var result={speech:station_string,status:station_string,heading:"Route of Train Number: "+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";
        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
}

/**
 * This function will return the seat availability as string.
 * Sample output : AVAILABLE 11

*/
exports.getJsonSeatAvailability = function (train_no, source, dest, date, _class, quota,eventCallback){

    var date_=new Date(date);
    var dd=date_.getDate();
    var mm=date_.getMonth()+1;
    var yy=date_.getFullYear();
    date=dd+"-"+mm+"-"+yy;
    var url =config.getBaseUrl() +'/check_seat/train/'+train_no+'/source/'+ source +'/dest/'+dest+'/date/'+ date+'/class/'+_class+'/quota/'+quota+'/apikey/'+ apiKey+'/';
    var status = "";
      http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var index3=0;
            var index4=0;
            var status=stringResult.availability[0].status;
            if(status.indexOf('AVAILABLE')>-1)
            {
                var index_=status.indexOf('AVAILABLE');
                var available=status.substring(index_+10);
            }
            status=available+" seats are available.";
            if(status.charAt(0)=='G'&&status.charAt(1)=='N'&&status.charAt(2)=='W')
               {
                 index3=status.indexOf("/WL");
                 index4=status.indexOf("\n",index3);
                 var waiting=status.substring(index3+3,index3+8);
                 var status=waiting+" seats are in waiting list.";
                }
                if(stringResult.response_code!='200')
                    status="There was an error processing your request.";

             var result={speech:status,status:status,heading:"Seat availability of Train: "+train_no};
             eventCallback(result);
        });
    }).on('error', function (e) {
             var result={speech:"Sorry, we could not process your request.",status:"Sorry, we could not process your request.",heading:null};
             eventCallback(result);
    });
}

/**
 * This function will return the train numbers of trains between stations as a string.
 * Sample output : 12617  16382  16346  19577  16334

*/
exports.getJsonTrainBtw =function (source, dest, date, eventCallback){
         var mon= date.substring(5,7);
         var day= date.substring(8);
         date=day+"-"+mon;
         var url=config.getBaseUrl()+"between/source/"+source+"/dest/"+dest+"/date/"+date+"/apikey/"+apiKey+"/";
         var stat="";
         var train_string="";
        http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var train_no=[];
            var src_departure_time=[];
            var dest_arrival_time=[];
            var days=[];
            var index=0;
            for(i=0; i<stringResult["train"].length; i++){
                days[i]="";
                train_no[i]=stringResult["train"][i].number;
                src_departure_time[i]=stringResult["train"][i].src_departure_time;
                dest_arrival_time[i]=stringResult["train"][i].dest_arrival_time;
                for  (j=0; j<stringResult["train"][i]["days"].length; j++){
                        if(stringResult["train"][i]["days"][j].runs==="Y")
                          {
                            switch(j){
                               case 0: days[i]=days[i]+"monday, ";
                                       break;
                               case 1: days[i]=days[i]+"tuesday, ";
                                       break;
                               case 2: days[i]=days[i]+"wednesday, ";
                                       break;
                               case 3: days[i]=days[i]+"thursday, ";
                                       break;
                               case 4: days[i]=days[i]+"friday, ";
                                       break;
                               case 5: days[i]=days[i]+"saturday, ";
                                       break;
                               case 6: days[i]=days[i]+"sunday, ";
                                       break;
                              }
                            }
                     }
              }
             stat= stat+ "Total "+i+" trains are there.";
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               if(m<=3)
                 {
                  stat = stat + " Train "+train_no[j]+ '.';
                   stat = stat+" Source departure time :"+src_departure_time[j]+", Destination arrival time "+dest_arrival_time[j]+", Days of run "+days[j]+".";
                   }
               train_string = train_string + "Train "+train_no[j]+ '\n';
               train_string =train_string+" Source departure time :"+src_departure_time[j]+"\n Destination arrival time "+dest_arrival_time[j]+"\n Days of run "+days[j]+"\n";

               }

               if(stringResult.response_code!='200'){
                    train_string="There was an error processing your request.";
                     stat=train_string;
                   }
             stat=stat+ "For details of all other trains see the result card."
             var result={speech:stat,status:train_string,heading:"Trains running between "+source+" and "+dest};
             eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        train_string = "sorry, we could not process your request.";
        var result={speech:train_string,status:train_string,heading:null};
        eventCallback(result);
    });
}

exports.getJsonPNRstatus=function (pnr_no, eventCallback){
    var result="";
    var stat="";
      var train_name="Hi";
     var url =config.getBaseUrl() +'pnr_status/pnr/'+pnr_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no;
            var doj="";
            var Class="";
            var chart_prepared="";
            var total_passengers;
            var booking_status=[];
            var current_status=[];
            var stringResult = JSON.parse(body);
             var c="";
            train_no= stringResult.train_no;
            doj= stringResult.doj;
            Class= stringResult.class;
            chart_prepared= stringResult.chart_prepared;
            total_passengers= stringResult.total_passengers;
           result= result+"Starting date is "+doj+"\n Class is "+Class+"\n Chart prepared "+chart_prepared+"\n Total number of passengers "+total_passengers+"\n Details of each passengers\n";

            for ( i=0; i<stringResult["passengers"].length; i++){
               booking_status[i]=stringResult["passengers"][i].booking_status;
               current_status[i]=stringResult["passengers"][i].current_status;

              }
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               result = result + "passenger "+m+ '\n';
               result=result+" Booking status "+booking_status[j]+"\n Current status "+current_status[j]+"\n";
               if(current_status[j].toUpperCase()==="CAN/MOD")
                  current_status[j]="cancelled or modified.";
              if((current_status[j].toUpperCase()==="CNF"))
                  {
                    current_status[j]="confirmed, Coach/Berth number will be available after chart preparation.";
                  }
               if(current_status[j].toUpperCase()==="CONFIRMED")
                  {
                    current_status[j]="confirmed, Coach/Berth number will be available after chart preparation.";
                  }
                else if(chart_prepared.toUpperCase()==="Y"){
                    c=current_status[j];
                    current_status[j]= "confirmed, coach and berth position is "+ c+".";
                }

               stat=stat+" passenger "+m+", current status is "+current_status[j]+".";
               }

               stat=stat+" For further details see the result card.";
                if(stringResult.response_code=='410'){
                    result="PNR does not exist.";
                    stat=result;
                   }
            var result1={speech:stat,status:result,heading:"PNR status of: "+pnr_no};

            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
        var result1={speech:result,status:result,heading:null};
        eventCallback(result1);
    });
}

exports.getJsonTrainArrivals=function (station_code,hrs, eventCallback){
    var result="";
    var url =config.getBaseUrl() +'arrivals/station/'+station_code+'/hours/'+hrs+'/apikey/'+ apiKey+'/';

    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no=[];
            var actdep=[];
            var delaydep=[];
            var scharr=[];
            var delayarr=[];
            var schdep =[];
            var stringResult = JSON.parse(body);
             for (i=0; i<stringResult["train"].length; i++){
                train_no[i]=stringResult["train"][i].number;
                scharr[i]=stringResult["train"][i].scharr;
                delayarr[i]=stringResult["train"][i].delayarr;
                schdep[i]=stringResult["train"][i].schdep;
                actdep[i]=stringResult["train"][i].actdep;
                delaydep[i]=stringResult["train"][i].delaydep;

              }
             var m=0;
            for ( j=0; j<i; j++){
               m=j+1;
               result = result + "Train "+train_no[j]+ '.';
               result=result+", Scheduled arrival "+scharr[j]+", Delayed arrival "+delayarr[j]+", Scheduled departure "+schdep[j]+", actual departure "+actdep[j]+", delayed departure "+delaydep[j]+".";

               }
               if(stringResult.response_code!='200')
                    result="There was an error processing your request.";
            var result1={speech:result,status:result,heading:"Train arrivals at station: "+station_code};
            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
         var result1={speech:result,status:result,heading:null};
         eventCallback(result1);
    });
}

/*exports.getJsonTrainName = function (train_no){
    var state="";
    var result="";
    var url =baseUrl +'/name_number/train/'+train_no+'/apikey/'+ apikey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.stringify(body);
            var index=0;
            var index2=0
            var train_numbers=[];
            var train_string="";
            var index=stringResult.indexOf("name")
            var index1=stringResult.indexOf("}",index)
            var name =stringResult.substring(index+10,index1-8);
            result=name;
            if(stringResult.indexOf("error") > -1) {
                 state = "error";
                }
            else
                 state = "success";

        });
    }).on('error', function (e) {
        state = "error";
    });
}

function numberToName(train_no,eventCallback){
    var baseURL="http://api.railwayapi.com";
    var apiKey="bkxel1825";
    var state="";
    var result="";
    var url =baseURL +'/name_number/train/'+train_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            eventCallback(stringResult.train.name);

        });
    }).on('error', function (e) {
        state = "error";
    });
}
*/

<commit_msg>for testing api exhaustion<commit_after>'use strict';
var config = require('../../configs');

var http = require('http');

/**
 *The AlexaSkill Module that has the AlexaSkill prototype and helper functions
 */

var apiKey=config.getAPIKey();
var i=0,j=0;
/**
 * This function will return the train status as a string.
 * Sample output : Train departed from KARUKKUTTY(KUC) and late by 24 minutes.
 */
exports.getJsonLiveStatus= function (train_no,doj,eventCallback){

    var url =config.getBaseUrl()+"live/train/"+train_no+"/doj/"+doj+"/apikey/"+apiKey+"/";
    var state="";
    var status= "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);

            var status=stringResult.position;
             if (stringResult.response_code=='403')
                  status=null;
            else  if(stringResult.response_code!='200')
                    status="There was an error processing your request.";
            var result={speech:status,status:stringResult.position,heading:'Train Number: '+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";

        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
   return status;
}

/**
 * This function will return the stations in a route as a string.
 * Sample output : KANYAKUMARI,Source,14:10,1,  NAGARCOIL JN,14:30,14:35,1,  KULITTHURAI,15:14,15:15,1,  TRIVANDRUM CNTL,15:55,16:00,1,  KOLLAM JN,17:00,17:05,1,  KAYANKULAM,17:34,17:36,1 (Station     **name,Arriavl time,Departure time,Day of arrival.)
 */
exports.getJsonTrainRoute=function (train_no,eventCallback){

    var url =config.getBaseUrl()+'route/train/'+train_no+'/apikey/'+ apiKey+'/';
       var station_string="";
    var state = "";
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var station_names=[];
            var station_arrival=[];
            var station_dep=[];
            var day=[];
            for (i=0; i<stringResult.route.length; i++){
                station_names[i]=stringResult.route[i].fullname;
                station_arrival[i]=stringResult.route[i].scharr;
                station_dep[i]=stringResult.route[i].schdep;
                day[i]=stringResult.route[i].day;
                }
             var m=0;
             var update=Math.ceil(((stringResult.route.length-2)/5));
             var source_=station_names[0];
             var dest_=station_names[i-1];

             station_string=station_string+"The train starts from "+source_+" at "+station_dep[0]+" and arrives  "+dest_+" at "+station_arrival[i-1]+" on day "+day[i-1]+" passing through ";
            for (j=0; j<i-1; j=j+update){
               m=j+1;
              if((j+update)<(i-1))
                 station_string=station_string+station_names[j]+",";
                else
                 station_string=station_string+" and "+station_names[j]+".";
               }
               if(stringResult.response_code!='200')
                    station_string="There was an error processing your request.";
            var result={speech:station_string,status:station_string,heading:"Route of Train Number: "+train_no};
            eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        status= "Sorry, we could not process your request.";
        var result={speech:status,status:status,heading:null};
        eventCallback(result);
    });
}

/**
 * This function will return the seat availability as string.
 * Sample output : AVAILABLE 11

*/
exports.getJsonSeatAvailability = function (train_no, source, dest, date, _class, quota,eventCallback){

    var date_=new Date(date);
    var dd=date_.getDate();
    var mm=date_.getMonth()+1;
    var yy=date_.getFullYear();
    date=dd+"-"+mm+"-"+yy;
    var url =config.getBaseUrl() +'/check_seat/train/'+train_no+'/source/'+ source +'/dest/'+dest+'/date/'+ date+'/class/'+_class+'/quota/'+quota+'/apikey/'+ apiKey+'/';
    var status = "";
      http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var index3=0;
            var index4=0;
            var status=stringResult.availability[0].status;
            if(status.indexOf('AVAILABLE')>-1)
            {
                var index_=status.indexOf('AVAILABLE');
                var available=status.substring(index_+10);
            }
            status=available+" seats are available.";
            if(status.charAt(0)=='G'&&status.charAt(1)=='N'&&status.charAt(2)=='W')
               {
                 index3=status.indexOf("/WL");
                 index4=status.indexOf("\n",index3);
                 var waiting=status.substring(index3+3,index3+8);
                 var status=waiting+" seats are in waiting list.";
                }
                if(stringResult.response_code!='200')
                    status="There was an error processing your request.";

             var result={speech:status,status:status,heading:"Seat availability of Train: "+train_no};
             eventCallback(result);
        });
    }).on('error', function (e) {
             var result={speech:"Sorry, we could not process your request.",status:"Sorry, we could not process your request.",heading:null};
             eventCallback(result);
    });
}

/**
 * This function will return the train numbers of trains between stations as a string.
 * Sample output : 12617  16382  16346  19577  16334

*/
exports.getJsonTrainBtw =function (source, dest, date, eventCallback){
         var mon= date.substring(5,7);
         var day= date.substring(8);
         date=day+"-"+mon;
         var url=config.getBaseUrl()+"between/source/"+source+"/dest/"+dest+"/date/"+date+"/apikey/"+apiKey+"/";
         var stat="";
         var train_string="";
        http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            var train_no=[];
            var src_departure_time=[];
            var dest_arrival_time=[];
            var days=[];
            var index=0;
            for(i=0; i<stringResult["train"].length; i++){
                days[i]="";
                train_no[i]=stringResult["train"][i].number;
                src_departure_time[i]=stringResult["train"][i].src_departure_time;
                dest_arrival_time[i]=stringResult["train"][i].dest_arrival_time;
                for  (j=0; j<stringResult["train"][i]["days"].length; j++){
                        if(stringResult["train"][i]["days"][j].runs==="Y")
                          {
                            switch(j){
                               case 0: days[i]=days[i]+"monday, ";
                                       break;
                               case 1: days[i]=days[i]+"tuesday, ";
                                       break;
                               case 2: days[i]=days[i]+"wednesday, ";
                                       break;
                               case 3: days[i]=days[i]+"thursday, ";
                                       break;
                               case 4: days[i]=days[i]+"friday, ";
                                       break;
                               case 5: days[i]=days[i]+"saturday, ";
                                       break;
                               case 6: days[i]=days[i]+"sunday, ";
                                       break;
                              }
                            }
                     }
              }
             stat= stat+ "Total "+i+" trains are there.";
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               if(m<=3)
                 {
                  stat = stat + " Train "+train_no[j]+ '.';
                   stat = stat+" Source departure time :"+src_departure_time[j]+", Destination arrival time "+dest_arrival_time[j]+", Days of run "+days[j]+".";
                   }
               train_string = train_string + "Train "+train_no[j]+ '\n';
               train_string =train_string+" Source departure time :"+src_departure_time[j]+"\n Destination arrival time "+dest_arrival_time[j]+"\n Days of run "+days[j]+"\n";

               }

               if(stringResult.response_code!='200'){
                    train_string="There was an error processing your request.";
                     stat=train_string;
                   }
             stat=stat+ "For details of all other trains see the result card."
             var result={speech:stat,status:train_string,heading:"Trains running between "+source+" and "+dest};
             eventCallback(result);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
        train_string = "sorry, we could not process your request.";
        var result={speech:train_string,status:train_string,heading:null};
        eventCallback(result);
    });
}

exports.getJsonPNRstatus=function (pnr_no, eventCallback){
    var result="";
    var stat="";
      var train_name="Hi";
     var url =config.getBaseUrl() +'pnr_status/pnr/'+pnr_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no;
            var doj="";
            var Class="";
            var chart_prepared="";
            var total_passengers;
            var booking_status=[];
            var current_status=[];
            var stringResult = JSON.parse(body);
             var c="";
            train_no= stringResult.train_no;
            doj= stringResult.doj;
            Class= stringResult.class;
            chart_prepared= stringResult.chart_prepared;
            total_passengers= stringResult.total_passengers;
           result= result+"Starting date is "+doj+"\n Class is "+Class+"\n Chart prepared "+chart_prepared+"\n Total number of passengers "+total_passengers+"\n Details of each passengers\n";

            for ( i=0; i<stringResult["passengers"].length; i++){
               booking_status[i]=stringResult["passengers"][i].booking_status;
               current_status[i]=stringResult["passengers"][i].current_status;

              }
             var m=0;
            for (j=0; j<i; j++){
               m=j+1;
               result = result + "passenger "+m+ '\n';
               result=result+" Booking status "+booking_status[j]+"\n Current status "+current_status[j]+"\n";
               if(current_status[j].toUpperCase()==="CAN/MOD")
                  current_status[j]="cancelled or modified.";
              if((current_status[j].toUpperCase()==="CNF"))
                  {
                    current_status[j]="confirmed, Coach/Berth number will be available after chart preparation.";
                  }
               if(current_status[j].toUpperCase()==="CONFIRMED")
                  {
                    current_status[j]="confirmed, Coach/Berth number will be available after chart preparation.";
                  }
                else if(chart_prepared.toUpperCase()==="Y"){
                    c=current_status[j];
                    current_status[j]= "confirmed, coach and berth position is "+ c+".";
                }

               stat=stat+" passenger "+m+", current status is "+current_status[j]+".";
               }

               stat=stat+" For further details see the result card.";
                if(stringResult.response_code=='410'){
                    result="PNR does not exist.";
                    stat=result;
                   }
            var result1={speech:stat,status:result,heading:"PNR status of: "+pnr_no};

            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
        var result1={speech:result,status:result,heading:null};
        eventCallback(result1);
    });
}

exports.getJsonTrainArrivals=function (station_code,hrs, eventCallback){
    var result="";
    var url =config.getBaseUrl() +'arrivals/station/'+station_code+'/hours/'+hrs+'/apikey/'+ apiKey+'/';

    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
           var train_no=[];
            var actdep=[];
            var delaydep=[];
            var scharr=[];
            var delayarr=[];
            var schdep =[];
            var stringResult = JSON.parse(body);
             for (i=0; i<stringResult["train"].length; i++){
                train_no[i]=stringResult["train"][i].number;
                scharr[i]=stringResult["train"][i].scharr;
                delayarr[i]=stringResult["train"][i].delayarr;
                schdep[i]=stringResult["train"][i].schdep;
                actdep[i]=stringResult["train"][i].actdep;
                delaydep[i]=stringResult["train"][i].delaydep;

              }
             var m=0;
            for ( j=0; j<i; j++){
               m=j+1;
               result = result + "Train "+train_no[j]+ '.';
               result=result+", Scheduled arrival "+scharr[j]+", Delayed arrival "+delayarr[j]+", Scheduled departure "+schdep[j]+", actual departure "+actdep[j]+", delayed departure "+delaydep[j]+".";

               }
               if(stringResult.response_code!='200')
                    result="There was an error processing your request.";
            var result1={speech:result,status:result,heading:"Train arrivals at station: "+station_code};
            eventCallback(result1);

        });
    }).on('error', function (e) {
        console.log("Got error: ", e);
         result = "sorry, we could not process your request.";
         var result1={speech:result,status:result,heading:null};
         eventCallback(result1);
    });
}

/*exports.getJsonTrainName = function (train_no){
    var state="";
    var result="";
    var url =baseUrl +'/name_number/train/'+train_no+'/apikey/'+ apikey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.stringify(body);
            var index=0;
            var index2=0
            var train_numbers=[];
            var train_string="";
            var index=stringResult.indexOf("name")
            var index1=stringResult.indexOf("}",index)
            var name =stringResult.substring(index+10,index1-8);
            result=name;
            if(stringResult.indexOf("error") > -1) {
                 state = "error";
                }
            else
                 state = "success";

        });
    }).on('error', function (e) {
        state = "error";
    });
}

function numberToName(train_no,eventCallback){
    var baseURL="http://api.railwayapi.com";
    var apiKey="bkxel1825";
    var state="";
    var result="";
    var url =baseURL +'/name_number/train/'+train_no+'/apikey/'+ apiKey+'/';
    http.get(url, function(res) {
        var body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () {
            var stringResult = JSON.parse(body);
            eventCallback(stringResult.train.name);

        });
    }).on('error', function (e) {
        state = "error";
    });
}
*/

<|endoftext|>


<commit_before>import ReadOnlyArrayProxy from 'ember-orbit/system/read-only-array-proxy';

export default ReadOnlyArrayProxy.extend({
  _orbitCache: null,
  _query: null,
  _identityMap: null,

  init(...args) {
    console.debug('creating liveQuery', this);
    this.set('content', Ember.A());

    this._super(...args);

    const orbitCache = this.get('_orbitCache');
    const query = this.get('_query');
    const orbitLiveQuery = orbitCache.liveQuery(query);

    orbitLiveQuery.subscribe((operation) => {
      console.debug('liveQuery', operation);

      const handler = `_${operation.op}`;

      if (!this[handler]) return;

      Ember.run(() => {
        this[handler](operation);
      });
    });
  },

  _addRecord(operation) {
    const record = this._recordFor(operation);
    this.get('content').pushObject(record);
  },

  _removeRecord(operation) {
    const record = this._recordFor(operation);
    this.get('content').removeObject(record);
  },

  _recordFor(operation) {
    const identityMap = this.get('_identityMap');
    const { type, id } = operation.record;
    return identityMap.lookup({id, type});
  }
});
<commit_msg>Simplify LiveQuery.<commit_after>import ReadOnlyArrayProxy from 'ember-orbit/system/read-only-array-proxy';
import Ember from 'ember';

const { get, set } = Ember;

export default ReadOnlyArrayProxy.extend({
  _orbitCache: null,
  _query: null,
  _identityMap: null,

  init(...args) {
    // console.debug('creating liveQuery', this);
    this._super(...args);

    set(this, 'content', Ember.A());

    const orbitLiveQuery = this._orbitCache.liveQuery(this._query);

    orbitLiveQuery.subscribe((operation) => {
      // console.debug('liveQuery', operation);

      const handler = `_${operation.op}`;

      if (!this[handler]) return;

      Ember.run(() => {
        this[handler](operation);
      });
    });
  },

  _addRecord(operation) {
    const record = this._recordFor(operation);
    get(this, 'content').pushObject(record);
  },

  _removeRecord(operation) {
    const record = this._recordFor(operation);
    get(this, 'content').removeObject(record);
  },

  _recordFor(operation) {
    return this._identityMap.lookup(operation.record);
  }
});
<|endoftext|>


<commit_before>'use strict';
angular.module("textAngularTest").controller('ButtonController', ['$http',  function($http) {
  /**
   * @return {string} A LaTeX command.
   */
  this.parseTag = function (match, tag, args) {
      result = '';
      switch (tag) {
        case 'h1':
          result += ' \\section*{';
          break;
        case '/h1':
          result += '} ';
          break;
        case 'h2':
          result += ' \\subsection*{';
          break;
        case '/h2':
          result += '} ';
          break;
        case 'p':
          result += ' \\par\\addvspace{\\medskipamount}\\noindent ';
          break;
        case '/p':
          result += ' ';
          break;
        case 'ul':
          result += ' \\begin{itemize} ';
          break;
        case '/ul':
          result += ' \\end{itemize} ';
          break;
        case 'ol':
          result += ' \\begin{enumerate} ';
          break;
        case '/ol':
          result += ' \\end{enumerate} ';
          break;
        case 'li':
          result += ' \\item ';
          break;
        case '/li':
          result += ' ';
          break;
        case 'b':
          result += '\\textbf{';
          break;
        case '/b':
          result += '}';
          break;
        case 'i':
          result += '\\textit{';
          break;
        case '/i':
          result += '}';
          break;
        case 'u':
          result += '\\underline{';
          break;
        case '/u':
          result += '}';
          break;
        case 'strike':
          result += '\\sout{';
          break;
        case '/strike':
          result += '}';
          break;
        case 'br/':
          result += ' ';
          break;
        default:
          result += '<' + tag + '>';
          break;
      }
      if (args) {
        // FIXME: this is a very quick and dirty way to process only
        // text-align arguments in the way as texAngulur produces them.
        var stylePart = /style="([^"]*)"/.exec(args);
        if (stylePart != null) {
          switch (stylePart[1]) {
            case 'text-align: center;':
              result += ' \\raggedleft{} ';
              break;
            case 'text-align: left;':
              result += '';
              break;
            case 'text-align: right;':
              result += '';
              break;
          }
        }
      }
  };

  /**
  * Take an HTML string and replace its tags with LaTeX commands.
  *
  * @param {string} htmlString The HTML string to parse.
  * @return {string} The corresponding LaTeX string.
  */
  this.tokenize = function (htmlString) {
    /**
     * General regular expressions in java script are a quite different, see:
     *   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions
     * string.replace is explained here:
     *   https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
     *
     * '([/a-zA-Z0-9]+)' is the second argument of tagsParse (the tag). A tag
     * may include '/' or word letters.
     * '([^<]*)' might be the third argument of tagsParse. This is for
     * example 'style="color: blue;"'.
     */
    var regularExpression = /<([/a-zA-Z0-9]+)(?:\s+([^<]*))?>/g;
    return htmlString.replace(regularExpression, this.parseTag);
  };

  /**
   * Add header and footer for latex document and tokenize given HTML-code.
   * @param  {string} html HTML-string generated by textAngular
   * @return {latex} Corresponding LaTeX-Code
   */
  this.html2latex = function(html){
    var texHead = '\\documentclass{juwit}\n \\begin{document}\n';
    var texBody = this.tokenize(html);
    var texTail = '\n \\end{document}\n';
    return texHead + texBody + texTail;
  };

  /**
  * Make a request to the server in order to get a pdf file.
  *
  * @param {string} htmlString String to generate pdf from HTML.
  */
  this.download = function(htmlString) {
    var latexString = this.html2latex(htmlString);
    $http.post("/compile", {"latexCode": latexString})
    .success(function(data, status, headers, config) {
      if (typeof data.redirect === 'string') {
        window.open(data.redirect, '_new', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
      }
    }).error(function(data, status, headers, config) {
      //TODO: Error Handling
    })
  };
}]);
<commit_msg>added text alignement<commit_after>'use strict';
angular.module("textAngularTest").controller('ButtonController', ['$http',  function($http) {
  /**
   * @return {string} A LaTeX command.
   */
  this.parseTag = function (match, tag, args) {
      result = '';
      switch (tag) {
        case 'h1':
          result += ' \\section*{';
          break;
        case '/h1':
          result += '} ';
          break;
        case 'h2':
          result += ' \\subsection*{';
          break;
        case '/h2':
          result += '} ';
          break;
        case 'p':
          result += ' \\par\\addvspace{\\medskipamount}\\noindent ';
          break;
        case '/p':
          result += ' ';
          break;
        case 'ul':
          result += ' \\begin{itemize} ';
          break;
        case '/ul':
          result += ' \\end{itemize} ';
          break;
        case 'ol':
          result += ' \\begin{enumerate} ';
          break;
        case '/ol':
          result += ' \\end{enumerate} ';
          break;
        case 'li':
          result += ' \\item ';
          break;
        case '/li':
          result += ' ';
          break;
        case 'b':
          result += '\\textbf{';
          break;
        case '/b':
          result += '}';
          break;
        case 'i':
          result += '\\textit{';
          break;
        case '/i':
          result += '}';
          break;
        case 'u':
          result += '\\underline{';
          break;
        case '/u':
          result += '}';
          break;
        case 'strike':
          result += '\\sout{';
          break;
        case '/strike':
          result += '}';
          break;
        case 'br/':
          result += ' ';
          break;
        default:
          result += '<' + tag + '>';
          break;
      }
      if (args) {
        // FIXME: this is a very quick and dirty way to process only
        // text-align arguments in the way as texAngulur produces them.
        var stylePart = /style="([^"]*)"/.exec(args);
        if (stylePart != null) {
          switch (stylePart[1]) {
            case 'text-align: center;':
              result += ' text-align ';
              break;
            case 'text-align: left;':
              result += ' text-align ';
              break;
            case 'text-align: right;':
              result += ' text-align ';
              break;
          }
        }
      }
      return result;
  };

  /**
  * Take an HTML string and replace its tags with LaTeX commands.
  *
  * @param {string} htmlString The HTML string to parse.
  * @return {string} The corresponding LaTeX string.
  */
  this.tokenize = function (htmlString) {
    /**
     * General regular expressions in java script are a quite different, see:
     *   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions
     * string.replace is explained here:
     *   https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
     *
     * '([/a-zA-Z0-9]+)' is the second argument of tagsParse (the tag). A tag
     * may include '/' or word letters.
     * '([^<]*)' might be the third argument of tagsParse. This is for
     * example 'style="color: blue;"'.
     */
    var regularExpression = /<([/a-zA-Z0-9]+)(?:\s+([^<]*))?>/g;
    return htmlString.replace(regularExpression, this.parseTag);
  };

  /**
   * Add header and footer for latex document and tokenize given HTML-code.
   * @param  {string} html HTML-string generated by textAngular
   * @return {latex} Corresponding LaTeX-Code
   */
  this.html2latex = function(html){
    var texHead = '\\documentclass{juwit}\n \\begin{document}\n';
    var texBody = this.tokenize(html);
    var texTail = '\n \\end{document}\n';
    return texHead + texBody + texTail;
  };

  /**
  * Make a request to the server in order to get a pdf file.
  *
  * @param {string} htmlString String to generate pdf from HTML.
  */
  this.download = function(htmlString) {
    var latexString = this.html2latex(htmlString);
    $http.post("/compile", {"latexCode": latexString})
    .success(function(data, status, headers, config) {
      if (typeof data.redirect === 'string') {
        window.open(data.redirect, '_new', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
      }
    }).error(function(data, status, headers, config) {
      //TODO: Error Handling
    })
  };
}]);
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');

var hopsConfig = require('hops-config');

function readSSLFile(fileName) {
  var filePath = path.resolve(__dirname, '..', 'ssl', fileName);
  return fs.readFileSync(filePath);
}

module.exports = function getHttpsConfig() {
  if (!hopsConfig.https) {
    return false;
  }
  return {
    key: readSSLFile('localhost.ssl.key'),
    cert: readSSLFile('localhost.ssl.crt'),
    ca: readSSLFile('rootca.pem'),
  };
};
<commit_msg>chore(build-config): get rid of remaining WDS config<commit_after><|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
const UserController = require(path + '/app/controllers/userController.server.js');
const PollController = require(path + '/app/controllers/pollController.server.js');

var _log = function(msg) {
    console.log("\t" + msg);
};

/** Function for debug logging request.*/
var reqDebug = function(req) {
	_log("Headers: " + JSON.stringify(req.headers));
	_log("Body: "    + JSON.stringify(req.body));
	_log("Params: "  + JSON.stringify(req.params));
	_log("Url:"      + JSON.stringify(req.url));
	_log("Text:"     + JSON.stringify(req.text));
	_log("Content:"  + JSON.stringify(req.content));
	_log("Query:"    + JSON.stringify(req.query));
};

module.exports = function (app, passport) {

    /** Renders a pug template.*/
    var renderPug = function(req, res, pugFile) {
        var isAuth = req.isAuthenticated();
        res.render(path + "/pug/" + pugFile, {isAuth: isAuth});
    };

    /** loggedIn func from clementine.js. */
	var isLoggedIn = function(req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

    var userController = new UserController(path);
	var pollController = new PollController(path, app.url);

	app.route('/')
		.get(function (req, res) {
            renderPug(req, res, "index.pug");
		});

	app.route('/signup')
		.get(function (req, res) {
            renderPug(req, res, "signup.pug");
		});

	app.route('/login')
		.get(function (req, res) {
            renderPug(req, res, "login.pug");
		});

	app.route('/loginFailed')
		.get(function (req, res) {
            res.render(path + "/pug/login.pug",
                {isAuth: false, loginFailed: true});
        });

    // If a user logs out, return to main page
	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/');
		});

    app.route('/create')
        .get(isLoggedIn, function(req, res) {
            renderPug(req, res, "create.pug");
        });

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
            renderPug(req, res, "profile.pug");
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post(function(req, res) {
            console.log("Got a signup form GET request..");
			reqDebug(req);
            userController.addLocalUser(req, res);
        });

    //----------------------------------------------------
    // Routes for getting/creating/deleting/updating polls
    //----------------------------------------------------

    app.route('/polls')
        .get(function(req, res) {
            pollController.getPolls(req, res);
        });

    app.route('/polls/create')
        .post(isLoggedIn, function(req, res) {
            pollController.addPoll(req, res);
        });

    app.route('/polls/vote/:id')
        .post(function(req, res) {
            pollController.addVoteOnPoll(req, res);
        });

    app.route('/polls/update/:id')
        .post(function(req, res) {
            pollController.updatePollById(req, res);
        });

    app.route('/polls/delete/:id')
        .get(function(req, res) {
            pollController.deletePollById(req, res);
        });

    app.route('/polls/getpolls/:id')
        .get(function(req, res) {
            pollController.getPollAsJSON(req, res);
        });

    app.route('/polls/:id')
        .get(function(req, res) {
            pollController.getPollById(req, res);
        });

    app.route('/p/:id')
        .get(function(req, res) {
            pollController.getPollByName(req, res);
        });
    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get(function (req, res) {
            userController.getUser(req, res);
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local',
            { failureRedirect: '/loginFailed' }),
		function(req, res) {
			res.redirect('/');
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/loginFailed'
		}));

};
<commit_msg>Wrapper log statements into if ().<commit_after>'use strict';

var path = process.cwd();
const UserController = require(path + '/app/controllers/userController.server.js');
const PollController = require(path + '/app/controllers/pollController.server.js');

var $DEBUG = 0;

var _log = function(msg) {
    console.log("\t" + msg);
};

/** Function for debug logging request.*/
var reqDebug = function(req) {
	_log("Headers: " + JSON.stringify(req.headers));
	_log("Body: "    + JSON.stringify(req.body));
	_log("Params: "  + JSON.stringify(req.params));
	_log("Url:"      + JSON.stringify(req.url));
	_log("Text:"     + JSON.stringify(req.text));
	_log("Content:"  + JSON.stringify(req.content));
	_log("Query:"    + JSON.stringify(req.query));
};

module.exports = function (app, passport) {

    /** Renders a pug template.*/
    var renderPug = function(req, res, pugFile) {
        var isAuth = req.isAuthenticated();
        res.render(path + "/pug/" + pugFile, {isAuth: isAuth});
    };

    /** loggedIn func from clementine.js. */
	var isLoggedIn = function(req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

    var userController = new UserController(path);
	var pollController = new PollController(path, app.url);

	app.route('/')
		.get(function (req, res) {
            renderPug(req, res, "index.pug");
		});

	app.route('/signup')
		.get(function (req, res) {
            renderPug(req, res, "signup.pug");
		});

	app.route('/login')
		.get(function (req, res) {
            renderPug(req, res, "login.pug");
		});

	app.route('/loginFailed')
		.get(function (req, res) {
            res.render(path + "/pug/login.pug",
                {isAuth: false, loginFailed: true});
        });

    // If a user logs out, return to main page
	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/');
		});

    app.route('/create')
        .get(isLoggedIn, function(req, res) {
            renderPug(req, res, "create.pug");
        });

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
            renderPug(req, res, "profile.pug");
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post(function(req, res) {
            if ($DEBUG) {
                console.log("Got a signup form GET request..");
                reqDebug(req);
            }
            userController.addLocalUser(req, res);
        });

    //----------------------------------------------------
    // Routes for getting/creating/deleting/updating polls
    //----------------------------------------------------

    app.route('/polls')
        .get(function(req, res) {
            pollController.getPolls(req, res);
        });

    app.route('/polls/create')
        .post(isLoggedIn, function(req, res) {
            pollController.addPoll(req, res);
        });

    app.route('/polls/vote/:id')
        .post(function(req, res) {
            pollController.addVoteOnPoll(req, res);
        });

    app.route('/polls/update/:id')
        .post(function(req, res) {
            pollController.updatePollById(req, res);
        });

    app.route('/polls/delete/:id')
        .get(function(req, res) {
            pollController.deletePollById(req, res);
        });

    app.route('/polls/getpolls/:id')
        .get(function(req, res) {
            pollController.getPollAsJSON(req, res);
        });

    app.route('/polls/:id')
        .get(function(req, res) {
            pollController.getPollById(req, res);
        });

    app.route('/p/:id')
        .get(function(req, res) {
            pollController.getPollByName(req, res);
        });
    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get(function (req, res) {
            userController.getUser(req, res);
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local',
            { failureRedirect: '/loginFailed' }),
		function(req, res) {
			res.redirect('/');
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/loginFailed'
		}));

};
<|endoftext|>


<commit_before>/* eslint-env mocha */
/* @flow */

import fs from 'fs-extra'
import _ from 'lodash'
import path from 'path'
import should from 'should'
import sinon from 'sinon'

import { scenarios, loadFSEventFiles, runActions, init } from '../helpers/scenarios'
import configHelpers from '../helpers/config'
import * as cozyHelpers from '../helpers/cozy'
import { IntegrationTestHelpers } from '../helpers/integration'
import pouchHelpers from '../helpers/pouch'
import remoteCaptureHelpers from '../../dev/capture/remote'

describe('test/scenarios/', () => {
  let helpers

  // Spies
  let prepCalls

  before(configHelpers.createConfig)
  before(configHelpers.registerClient)
  beforeEach(pouchHelpers.createDatabase)
  beforeEach(cozyHelpers.deleteAll)
  beforeEach('set up synced dir', async function () {
    await fs.emptyDir(this.syncPath)
  })
  beforeEach('set up outside dir', async function () {
    await fs.emptyDir(path.resolve(path.join(this.syncPath, '..', 'outside')))
  })

  afterEach(pouchHelpers.cleanDatabase)
  after(configHelpers.cleanConfig)

  beforeEach(async function () {
    helpers = new IntegrationTestHelpers(this.config, this.pouch, cozyHelpers.cozy)
    // TODO: Spy in IntegrationTestHelpers by default
    prepCalls = []

    for (let method of ['addFileAsync', 'putFolderAsync', 'updateFileAsync',
      'moveFileAsync', 'moveFolderAsync', 'deleteFolderAsync', 'trashFileAsync',
      'trashFolderAsync', 'restoreFileAsync', 'restoreFolderAsync']) {

      // $FlowFixMe
      const origMethod = helpers.prep[method]
      sinon.stub(helpers.prep, method).callsFake(async (...args) => {
        const call: Object = {method}
        if (method.startsWith('move') || method.startsWith('restore')) {
          call.dst = args[1].path
          call.src = args[2].path
        } else {
          call.path = args[1].path
        }
        prepCalls.push(call)

        // Call the actual method so we can make assertions on metadata & FS
        return origMethod.apply(helpers.prep, args)
      })
    }

    // TODO: helpers.setup()
    await helpers.local.setupTrash()
    await helpers.remote.ignorePreviousChanges()
  })

  afterEach(function () {
    // TODO: Include prep actions in custom assertion
    if (this.currentTest.state === 'failed') {
      // TODO: dump logs
    }
  })

  for (let scenario of scenarios) {
    describe(`${scenario.name}/`, () => {
      describe('local/', () => {
        if (scenario.init) {
          beforeEach('init', async function () {
            let relpathFix = _.identity
            if (process.platform === 'win32' && this.currentTest.title.match(/win32/)) {
              relpathFix = (relpath) => relpath.replace(/\//g, '\\').toUpperCase()
            }
            await init(scenario, this.pouch, helpers.local.syncDir.abspath, relpathFix)
          })
        }

        beforeEach('actions', () => runActions(scenario, helpers.local.syncDir.abspath))

        for (let eventsFile of loadFSEventFiles(scenario)) {
          if (process.platform === 'win32' && eventsFile.name.indexOf('win32') === -1) {
            it.skip(`${eventsFile.name}`, () => {})
            continue
          }

          it(eventsFile.name, async function () {
            await helpers.local.simulateEvents(eventsFile.events)
            await helpers.syncAll()

            // TODO: Wrap in custom expectation
            if (scenario.expected) {
              const expectedLocalTree = scenario.expected.tree || scenario.expected.localTree
              const expectedRemoteTree = scenario.expected.tree || scenario.expected.remoteTree
              delete scenario.expected.tree
              delete scenario.expected.prepCalls // TODO: expect prep actions
              const actual = {}

              if (expectedLocalTree) {
                scenario.expected.localTree = expectedLocalTree
                actual.localTree = await helpers.local.tree()
              }
              if (expectedRemoteTree) {
                scenario.expected.remoteTree = expectedRemoteTree
                actual.remoteTree = await helpers.remote.treeWithoutTrash()
              }
              if (scenario.expected.remoteTrash) {
                actual.remoteTrash = await helpers.remote.trash()
              }

              should(actual).deepEqual(scenario.expected)
            }

            // TODO: pull
          })
        } // event files
      }) // local

      describe('remote/', () => {
        if (scenario.init) {
          beforeEach('init', async function () {
            await init(scenario, this.pouch, helpers.local.syncDir.abspath, _.identity)
            await helpers.remote.ignorePreviousChanges()
          })
        }

        beforeEach('actions', async () => {
          await remoteCaptureHelpers.runActions(scenario, cozyHelpers.cozy)
        })

        if (scenario.name.indexOf('outside') !== -1) {
          it.skip(`no outside on remote`, () => {})
          return
        }

        it('works', async function () {
          await helpers.remote.pullChanges()
          for (let i = 0; i < scenario.actions.length + 1; i++) {
            await helpers.syncAll()
          }

          if (scenario.expected && scenario.expected.tree) {
            if (scenario.expected.prepCalls) {
              should(prepCalls).deepEqual(scenario.expected.prepCalls)
            }
            should(await helpers.local.treeWithoutTrash())
              .deepEqual(scenario.expected.tree)
          }
        }) // changes file test
      }) // describe remote
    }) // scenario
  } // scenarios
})
<commit_msg>test/integration/scenarios: Ensure test names match scenario's local files / remote dirs<commit_after>/* eslint-env mocha */
/* @flow */

import fs from 'fs-extra'
import _ from 'lodash'
import path from 'path'
import should from 'should'
import sinon from 'sinon'

import { scenarios, loadFSEventFiles, runActions, init } from '../helpers/scenarios'
import configHelpers from '../helpers/config'
import * as cozyHelpers from '../helpers/cozy'
import { IntegrationTestHelpers } from '../helpers/integration'
import pouchHelpers from '../helpers/pouch'
import remoteCaptureHelpers from '../../dev/capture/remote'

let helpers

// Spies
let prepCalls

before(configHelpers.createConfig)
before(configHelpers.registerClient)
beforeEach(pouchHelpers.createDatabase)
beforeEach(cozyHelpers.deleteAll)
beforeEach('set up synced dir', async function () {
  await fs.emptyDir(this.syncPath)
})
beforeEach('set up outside dir', async function () {
  await fs.emptyDir(path.resolve(path.join(this.syncPath, '..', 'outside')))
})

afterEach(pouchHelpers.cleanDatabase)
after(configHelpers.cleanConfig)

beforeEach(async function () {
  helpers = new IntegrationTestHelpers(this.config, this.pouch, cozyHelpers.cozy)
  // TODO: Spy in IntegrationTestHelpers by default
  prepCalls = []

  for (let method of ['addFileAsync', 'putFolderAsync', 'updateFileAsync',
    'moveFileAsync', 'moveFolderAsync', 'deleteFolderAsync', 'trashFileAsync',
    'trashFolderAsync', 'restoreFileAsync', 'restoreFolderAsync']) {
    // $FlowFixMe
    const origMethod = helpers.prep[method]
    sinon.stub(helpers.prep, method).callsFake(async (...args) => {
      const call: Object = {method}
      if (method.startsWith('move') || method.startsWith('restore')) {
        call.dst = args[1].path
        call.src = args[2].path
      } else {
        call.path = args[1].path
      }
      prepCalls.push(call)

      // Call the actual method so we can make assertions on metadata & FS
      return origMethod.apply(helpers.prep, args)
    })
  }

  // TODO: helpers.setup()
  await helpers.local.setupTrash()
  await helpers.remote.ignorePreviousChanges()
})

afterEach(function () {
  // TODO: Include prep actions in custom assertion
  if (this.currentTest.state === 'failed') {
    // TODO: dump logs
  }
})

for (let scenario of scenarios) {
  for (let eventsFile of loadFSEventFiles(scenario)) {
    if (process.platform === 'win32' && eventsFile.name.indexOf('win32') === -1) {
      it.skip(`${eventsFile.name}`, () => {})
      continue
    }

    it(`test/scenarios/${scenario.name}/local/${eventsFile.name}`, async function () {
      if (scenario.init) {
        let relpathFix = _.identity
        if (process.platform === 'win32' && this.currentTest.title.match(/win32/)) {
          relpathFix = (relpath) => relpath.replace(/\//g, '\\').toUpperCase()
        }
        await init(scenario, this.pouch, helpers.local.syncDir.abspath, relpathFix)
      }

      await runActions(scenario, helpers.local.syncDir.abspath)
      await helpers.local.simulateEvents(eventsFile.events)
      await helpers.syncAll()

      // TODO: Wrap in custom expectation
      if (scenario.expected) {
        const expectedLocalTree = scenario.expected.tree || scenario.expected.localTree
        const expectedRemoteTree = scenario.expected.tree || scenario.expected.remoteTree
        delete scenario.expected.tree
        delete scenario.expected.prepCalls // TODO: expect prep actions
        const actual = {}

        if (expectedLocalTree) {
          scenario.expected.localTree = expectedLocalTree
          actual.localTree = await helpers.local.tree()
        }
        if (expectedRemoteTree) {
          scenario.expected.remoteTree = expectedRemoteTree
          actual.remoteTree = await helpers.remote.treeWithoutTrash()
        }
        if (scenario.expected.remoteTrash) {
          actual.remoteTrash = await helpers.remote.trash()
        }

        should(actual).deepEqual(scenario.expected)
      }

      // TODO: pull
    })
  } // event files

  if (scenario.name.indexOf('outside') !== -1) {
    it.skip(`no outside on remote`, () => {})
    continue
  }

  it(`test/scenarios/${scenario.name}/remote/`, async function () {
    if (scenario.init) {
      await init(scenario, this.pouch, helpers.local.syncDir.abspath, _.identity)
      await helpers.remote.ignorePreviousChanges()
    }

    await remoteCaptureHelpers.runActions(scenario, cozyHelpers.cozy)

    await helpers.remote.pullChanges()
    for (let i = 0; i < scenario.actions.length + 1; i++) {
      await helpers.syncAll()
    }

    if (scenario.expected && scenario.expected.tree) {
      if (scenario.expected.prepCalls) {
        should(prepCalls).deepEqual(scenario.expected.prepCalls)
      }
      should(await helpers.local.treeWithoutTrash())
        .deepEqual(scenario.expected.tree)
    }
  }) // describe remote
} // scenarios
<|endoftext|>


<commit_before>var Plurb = require('../db/dbconfig').Plurb;

module.exports = {
  getAllPlurbs: function (req, res) {
    Plurb.findAll({})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  createPlurb: function (req, res) {
    var plurbData = {
      text: req.body.text,
      location: JSON.stringify(req.body.location),
    };
    Plurb.create(plurbData)
    .then(function (plurb) {
      plurb.setUser(req.session.user);
      //plurb.setTopic(TODO:);
      res.status(201).json(plurb);
    })
    .catch(function (err) {
      console.error (err);
    });
  },

  getPlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.findById(plurbId)
    .then(function (plurb) {
      res.status(200).json(plurb);
    })
    .catch(function (err) {
      console.error (err);
    });
  },

  deletePlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.destroy({where: {id: plurbId}})
    .then(function () {
      res.status(201);
    })
    .catch(function (err) {
      console.error (err);
    });
  },

  getPlurbsByGoogId: function (req, res) {
    var googId = req.params.googId;
    Plurb.findAll({where: {UserGoogid: googId}})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error (err);
    });
  }
};
<commit_msg>(feat) Pull topic from request for createPlurb controller<commit_after>var Plurb = require('../db/dbconfig').Plurb;

module.exports = {
  getAllPlurbs: function (req, res) {
    Plurb.findAll({})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error(err);
    });
  },

  createPlurb: function (req, res) {
    var plurbData = {
      text: req.body.text,
      location: JSON.stringify(req.body.location),
      topic: req.body.topic
    };
    Plurb.create(plurbData)
    .then(function (plurb) {
      plurb.setUser(req.session.user);
      //plurb.setTopic(TODO:);
      res.status(201).json(plurb);
    })
    .catch(function (err) {
      console.error (err);
    });
  },

  getPlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.findById(plurbId)
    .then(function (plurb) {
      res.status(200).json(plurb);
    })
    .catch(function (err) {
      console.error (err);
    });
  },

  deletePlurb: function (req, res) {
    var plurbId = req.params.plurbId;
    Plurb.destroy({where: {id: plurbId}})
    .then(function () {
      res.status(201);
    })
    .catch(function (err) {
      console.error (err);
    });
  },

  getPlurbsByGoogId: function (req, res) {
    var googId = req.params.googId;
    Plurb.findAll({where: {UserGoogid: googId}})
    .then(function (plurbs) {
      res.status(200).json(plurbs);
    })
    .catch(function (err) {
      console.error (err);
    });
  }
};
<|endoftext|>


<commit_before>/*!
 * Copyright 2015 mifort.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

angular.module('mifortTimelog.report', ['ngRoute'])

    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/report', {
            templateUrl: 'report/reportView.html',
            controller: 'reportController'
        });
    }])

    .controller('reportController', ['$scope', 'reportService', 'preferences', 'uiGridConstants', 'topPanelService', function($scope, reportService, preferences, uiGridConstants, topPanelService) {
        var companyId = preferences.get('user').companyId,
            headerHeight = 38;

        $scope.ranges = {
            'Today': [moment(), moment()],
            //'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 days': [moment().subtract(7, 'days'), moment()],
            'Last 30 days': [moment().subtract(30, 'days'), moment()],
            'This month': [moment().startOf('month'), moment().endOf('month')]
        };

        $scope.reportColumns = ['Data', 'User', 'Project', 'Assignment', 'Time', 'Action'];
        $scope.perPage = [5, 10, 20, 50, 100];
        $scope.totalCount = 0;
        $scope.projects = [];

        $scope.reportSettings = {
            companyId: companyId,
            sort: {
                field: 'date',
                asc: true
            },
            filters: [],
            pageSize: 5,
            page: 1
        };

        $scope.gridOptions = {
            ranges: $scope.ranges,
            paginationPageSizes: [25, 50, 75],
            paginationPageSize: 25,
            enableFiltering: true,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,
            rowHeight: 30,
            columnDefs: [
                {
                    field: 'date',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'userName',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'projectName',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'role',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    cellTemplate: '
{{row.entity.role.role}}
',
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'time',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                }
            ],
            data: 'reportData',

            onRegisterApi: function(gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, $scope.sortChanged);
                $scope.sortChanged($scope.gridApi.grid, [$scope.gridOptions.columnDefs[1]]);
            }
        };

        $scope.sortChanged = function(grid, sortColumns) {
            $scope.reportSettings.page = 1;

            if(sortColumns.length === 0 || !sortColumns[0].sort){
                $scope.getReport();
            }else{
                switch(sortColumns[0].sort.direction){
                    case uiGridConstants.ASC:
                        $scope.reportSettings.sort = {
                            field: sortColumns[0].field,
                            asc: true
                        };
                        break;

                    case uiGridConstants.DESC:
                        $scope.reportSettings.sort = {
                            field: sortColumns[0].field,
                            asc: false
                        };
                        break;
                }

                $scope.getReport();
            }
        };

        reportService.getFilters(companyId).success(function(data) {
            $scope.filtersSettings = data;

            $scope.gridOptions.reportFilters = data;
        });

        $scope.$watch('gridOptions.reportFilters', function(newValue, oldValue) {
            if(newValue && newValue != oldValue){
                $scope.reportSettings.filters = [];

                var dateFilter = _.where(newValue, {field: 'date'})[0];

                if(dateFilter){
                    $scope.reportSettings.filters.push(dateFilter)
                }

                newValue.forEach(function(filter) {
                    var filterToPush = {
                            field: filter.field
                        },
                        checkedFilters = _.where(filter.value, {isChecked: true});

                    filterToPush.value = checkedFilters.map(function(checkedFilter) {
                        return checkedFilter.name
                    });

                    if(filterToPush.value.length){
                        $scope.reportSettings.filters.push(filterToPush);
                    }
                });

                $scope.getReport();
            }
        }, true);

        $scope.getReport = function() {
            reportService.getReport($scope.reportSettings).success(function(data, status, headers) {
                $scope.reportData = data;

                $scope.gridHeight = {
                    height: ((data.length) * ($scope.gridOptions.rowHeight + 1)) + headerHeight + "px"
                };

                if(headers()['x-total-count']){
                    $scope.totalCount = headers()['x-total-count'];
                    $scope.totalPages = Math.ceil($scope.totalCount / $scope.reportSettings.pageSize);
                }
            });
        };

        $scope.openPage = function(pageIndex) {
            $scope.reportSettings.page = pageIndex;
            $scope.getReport();
        };

        $scope.nextPage = function() {
            if($scope.reportSettings.page < $scope.totalPages){
                $scope.reportSettings.page++;
                $scope.getReport();
            }
        };

        $scope.prevPage = function() {
            if($scope.reportSettings.page > 1){
                $scope.reportSettings.page--;
                $scope.getReport();
            }
        };

        $scope.range = function(n) {
            return new Array(n);
        };

        $scope.downloadCsv = function() {
            reportService.downloadCsv($scope.reportSettings).success(function(data) {
                window.location = data.url;
            });
        };

        $scope.perPageChanged = function() {
            $scope.reportSettings.page = 1;
            $scope.getReport();
        };

        $scope.$on('handleBroadcast', function() {
            if(topPanelService.linkName = 'report'){
                $scope.downloadCsv();
            }
        });
        //
        //$scope.dateFilterChanged = function(dates) {
        //    var dateFilter = {
        //        "field": "date",
        //        "start": moment(new Date(dates.startDate)).format('MM/DD/YYYY'),
        //        "end": moment(new Date(dates.endDate)).format('MM/DD/YYYY')
        //    };
        //
        //    $scope.reportSettings.filters.push(dateFilter);
        //    $scope.getReport();
        //}
    }]);<commit_msg>Reports Role fix<commit_after>/*!
 * Copyright 2015 mifort.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

angular.module('mifortTimelog.report', ['ngRoute'])

    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/report', {
            templateUrl: 'report/reportView.html',
            controller: 'reportController'
        });
    }])

    .controller('reportController', ['$scope', 'reportService', 'preferences', 'uiGridConstants', 'topPanelService', function($scope, reportService, preferences, uiGridConstants, topPanelService) {
        var companyId = preferences.get('user').companyId,
            headerHeight = 38;

        $scope.ranges = {
            'Today': [moment(), moment()],
            //'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 days': [moment().subtract(7, 'days'), moment()],
            'Last 30 days': [moment().subtract(30, 'days'), moment()],
            'This month': [moment().startOf('month'), moment().endOf('month')]
        };

        $scope.reportColumns = ['Data', 'User', 'Project', 'Assignment', 'Time', 'Action'];
        $scope.perPage = [5, 10, 20, 50, 100];
        $scope.totalCount = 0;
        $scope.projects = [];

        $scope.reportSettings = {
            companyId: companyId,
            sort: {
                field: 'date',
                asc: true
            },
            filters: [],
            pageSize: 5,
            page: 1
        };

        $scope.gridOptions = {
            ranges: $scope.ranges,
            paginationPageSizes: [25, 50, 75],
            paginationPageSize: 25,
            enableFiltering: true,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,
            rowHeight: 30,
            columnDefs: [
                {
                    field: 'date',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'userName',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'projectName',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'role',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    cellTemplate: '
{{row.entity.role}}
',
                    filterHeaderTemplate: '

'
                },
                {
                    field: 'time',
                    enableColumnResizing: true,
                    enableColumnMenu: false,
                    filterHeaderTemplate: '

'
                }
            ],
            data: 'reportData',

            onRegisterApi: function(gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, $scope.sortChanged);
                $scope.sortChanged($scope.gridApi.grid, [$scope.gridOptions.columnDefs[1]]);
            }
        };

        $scope.sortChanged = function(grid, sortColumns) {
            $scope.reportSettings.page = 1;

            if(sortColumns.length === 0 || !sortColumns[0].sort){
                $scope.getReport();
            }else{
                switch(sortColumns[0].sort.direction){
                    case uiGridConstants.ASC:
                        $scope.reportSettings.sort = {
                            field: sortColumns[0].field,
                            asc: true
                        };
                        break;

                    case uiGridConstants.DESC:
                        $scope.reportSettings.sort = {
                            field: sortColumns[0].field,
                            asc: false
                        };
                        break;
                }

                $scope.getReport();
            }
        };

        reportService.getFilters(companyId).success(function(data) {
            $scope.filtersSettings = data;

            $scope.gridOptions.reportFilters = data;
        });

        $scope.$watch('gridOptions.reportFilters', function(newValue, oldValue) {
            if(newValue && newValue != oldValue){
                $scope.reportSettings.filters = [];

                var dateFilter = _.where(newValue, {field: 'date'})[0];

                if(dateFilter){
                    $scope.reportSettings.filters.push(dateFilter)
                }

                newValue.forEach(function(filter) {
                    var filterToPush = {
                            field: filter.field
                        },
                        checkedFilters = _.where(filter.value, {isChecked: true});

                    filterToPush.value = checkedFilters.map(function(checkedFilter) {
                        return checkedFilter.name
                    });

                    if(filterToPush.value.length){
                        $scope.reportSettings.filters.push(filterToPush);
                    }
                });

                $scope.getReport();
            }
        }, true);

        $scope.getReport = function() {
            reportService.getReport($scope.reportSettings).success(function(data, status, headers) {
                $scope.reportData = data;

                $scope.gridHeight = {
                    height: ((data.length) * ($scope.gridOptions.rowHeight + 1)) + headerHeight + "px"
                };

                if(headers()['x-total-count']){
                    $scope.totalCount = headers()['x-total-count'];
                    $scope.totalPages = Math.ceil($scope.totalCount / $scope.reportSettings.pageSize);
                }
            });
        };

        $scope.openPage = function(pageIndex) {
            $scope.reportSettings.page = pageIndex;
            $scope.getReport();
        };

        $scope.nextPage = function() {
            if($scope.reportSettings.page < $scope.totalPages){
                $scope.reportSettings.page++;
                $scope.getReport();
            }
        };

        $scope.prevPage = function() {
            if($scope.reportSettings.page > 1){
                $scope.reportSettings.page--;
                $scope.getReport();
            }
        };

        $scope.range = function(n) {
            return new Array(n);
        };

        $scope.downloadCsv = function() {
            reportService.downloadCsv($scope.reportSettings).success(function(data) {
                window.location = data.url;
            });
        };

        $scope.perPageChanged = function() {
            $scope.reportSettings.page = 1;
            $scope.getReport();
        };

        $scope.$on('handleBroadcast', function() {
            if(topPanelService.linkName = 'report'){
                $scope.downloadCsv();
            }
        });
        //
        //$scope.dateFilterChanged = function(dates) {
        //    var dateFilter = {
        //        "field": "date",
        //        "start": moment(new Date(dates.startDate)).format('MM/DD/YYYY'),
        //        "end": moment(new Date(dates.endDate)).format('MM/DD/YYYY')
        //    };
        //
        //    $scope.reportSettings.filters.push(dateFilter);
        //    $scope.getReport();
        //}
    }]);<|endoftext|>


<commit_before>import Ember from 'ember';
import { extend } from './utils';

function detect(obj) {
  return obj.isViewClass || this._super(obj);
}

Ember.CoreView.reopenClass({
  detect: detect
});

Ember.View.reopenClass({
  detect: detect
});

var metaFor = Ember.meta;
var finishPartial = Ember.Mixin.finishPartial;
var IS_BINDING = Ember.IS_BINDING;
var computed = Ember.computed;
var get = Ember.get;

function MetalView(props) {
  this.isView = true;
  this.tagName = null;
  this.isVirtual = false;
  this.elementId = null;
  this._keywords = undefined;
  this._baseContext = undefined;
  this._contextStream = undefined;
  this._streamBindings = undefined;

  var meta = metaFor(this); // FIXME
  var proto = meta.proto;
  meta.proto = this; // Secret handshake to prevent observers firing during init

  var bindings = meta.bindings = meta.bindings || {};
  var possibleDesc;
  var desc;
  for (var key in props) {
    if (!props.hasOwnProperty(key)) { continue; }
    if (IS_BINDING.test(key)) {
      bindings[key] = props[key];
    }
    possibleDesc = this[key];
    desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;
    if (desc) {
      desc.set(this, key, props[key]);
    } else {
      this[key] = props[key];
    }
  }

  if (!this.isVirtual && !this.elementId) {
    this.elementId = Ember.guidFor(this);
  }

  finishPartial(this, meta);
  this.init();
  meta.proto = proto;
}

MetalView.prototype.__ember_meta__ = metaFor(MetalView.prototype);
MetalView.prototype.__ember_meta__.proto = MetalView.prototype;

Ember.defineProperty(MetalView.prototype, 'parentView', computed('_parentView', function() {
  var parent = this._parentView;

  if (parent && parent.isVirtual) {
    return get(parent, 'parentView');
  } else {
    return parent;
  }
}));

extend(MetalView.prototype, {

  _childViews: [],

  // TODO: remove this
  currentState: {
    appendChild: function(view, childView, options) {
      var buffer = view.buffer;
      var _childViews = view._childViews;

      childView = view.createChildView(childView, options);
      if (!_childViews.length) { _childViews = view._childViews = _childViews.slice(); }
      _childViews.push(childView);

      if (!childView._morph) {
        buffer.pushChildView(childView);
      }

      view.propertyDidChange('childViews');

      return childView;
    },

    invokeObserver: function(target, observer) {
      observer.call(target);
    }
  },

  propertyDidChange: function() {},

  destroy: function() {
    // TODO: EmberObject#destroy stuff?

    if (!this.removedFromDOM && this._renderer) {
      this._renderer.remove(this, true);
    }

    // remove from parent if found. Don't call removeFromParent,
    // as removeFromParent will try to remove the element from
    // the DOM again.
    var parent = this._parentView;
    if (parent) { parent.removeChild(this); }

    this._transitionTo('destroying', false);

    return this;
  },

  destroyElement: function() {
    var state = this._state;
    if (state === 'destroying') {
      throw 'destroyElement'; // TODO
    }
    if (this._renderer) {
      this._renderer.remove(this, false);
    }
    return this;
  },

  _transitionTo: function(state) {
    this._state = state;
  },

  __defineNonEnumerable: function(property) {
    this[property.name] = property.descriptor.value;
  },

  _wrapAsScheduled: Ember.View.proto()._wrapAsScheduled
});

var EmberViewModule = Ember.__loader.require('ember-views/views/view');

EmberViewModule.ViewKeywordSupport.apply(MetalView.prototype);
EmberViewModule.ViewStreamSupport.apply(MetalView.prototype);
EmberViewModule.ViewChildViewsSupport.apply(MetalView.prototype);
EmberViewModule.ViewContextSupport.apply(MetalView.prototype);
EmberViewModule.TemplateRenderingSupport.apply(MetalView.prototype);

var Evented = Ember.__loader.require('ember-runtime/mixins/evented')['default'];
Evented.apply(MetalView.prototype);

extend(MetalView, {
  classProps: ['classProps', 'isClass', 'isViewClass', 'isMethod', 'proto', 'create', 'extend', 'reopenClass'],
  isClass: true,
  isViewClass: true,
  isMethod: false,

  proto: function() {
    return MetalView.prototype;
  },

  create: function(props) {
    return new this(props);
  },

  extend: function(props) {
    var ParentClass = this;
    var Subclass = function(props) { ParentClass.call(this, props); };
    Subclass.superclass = ParentClass;
    var classProps = ParentClass.classProps;
    var key;
    for (var i = 0, l = classProps.length; i < l; i++) {
      key = classProps[i];
      Subclass[key] = this[key];
    }
    Subclass.prototype = Ember.create(this.prototype);
    if (props) { extend(Subclass.prototype, props); }
    return Subclass;
  },

  reopenClass: function(props) {
    extend(this, props);
  }
});

export default MetalView;
<commit_msg>Remove unnecessary detect overrides<commit_after>import Ember from 'ember';
import { extend } from './utils';

var metaFor = Ember.meta;
var finishPartial = Ember.Mixin.finishPartial;
var IS_BINDING = Ember.IS_BINDING;
var computed = Ember.computed;
var get = Ember.get;

function MetalView(props) {
  this.isView = true;
  this.tagName = null;
  this.isVirtual = false;
  this.elementId = null;
  this._keywords = undefined;
  this._baseContext = undefined;
  this._contextStream = undefined;
  this._streamBindings = undefined;

  var meta = metaFor(this); // FIXME
  var proto = meta.proto;
  meta.proto = this; // Secret handshake to prevent observers firing during init

  var bindings = meta.bindings = meta.bindings || {};
  var possibleDesc;
  var desc;
  for (var key in props) {
    if (!props.hasOwnProperty(key)) { continue; }
    if (IS_BINDING.test(key)) {
      bindings[key] = props[key];
    }
    possibleDesc = this[key];
    desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;
    if (desc) {
      desc.set(this, key, props[key]);
    } else {
      this[key] = props[key];
    }
  }

  if (!this.isVirtual && !this.elementId) {
    this.elementId = Ember.guidFor(this);
  }

  finishPartial(this, meta);
  this.init();
  meta.proto = proto;
}

MetalView.prototype.__ember_meta__ = metaFor(MetalView.prototype);
MetalView.prototype.__ember_meta__.proto = MetalView.prototype;

Ember.defineProperty(MetalView.prototype, 'parentView', computed('_parentView', function() {
  var parent = this._parentView;

  if (parent && parent.isVirtual) {
    return get(parent, 'parentView');
  } else {
    return parent;
  }
}));

extend(MetalView.prototype, {

  _childViews: [],

  // TODO: remove this
  currentState: {
    appendChild: function(view, childView, options) {
      var buffer = view.buffer;
      var _childViews = view._childViews;

      childView = view.createChildView(childView, options);
      if (!_childViews.length) { _childViews = view._childViews = _childViews.slice(); }
      _childViews.push(childView);

      if (!childView._morph) {
        buffer.pushChildView(childView);
      }

      view.propertyDidChange('childViews');

      return childView;
    },

    invokeObserver: function(target, observer) {
      observer.call(target);
    }
  },

  propertyDidChange: function() {},

  destroy: function() {
    // TODO: EmberObject#destroy stuff?

    if (!this.removedFromDOM && this._renderer) {
      this._renderer.remove(this, true);
    }

    // remove from parent if found. Don't call removeFromParent,
    // as removeFromParent will try to remove the element from
    // the DOM again.
    var parent = this._parentView;
    if (parent) { parent.removeChild(this); }

    this._transitionTo('destroying', false);

    return this;
  },

  destroyElement: function() {
    var state = this._state;
    if (state === 'destroying') {
      throw 'destroyElement'; // TODO
    }
    if (this._renderer) {
      this._renderer.remove(this, false);
    }
    return this;
  },

  _transitionTo: function(state) {
    this._state = state;
  },

  __defineNonEnumerable: function(property) {
    this[property.name] = property.descriptor.value;
  },

  _wrapAsScheduled: Ember.View.proto()._wrapAsScheduled
});

var EmberViewModule = Ember.__loader.require('ember-views/views/view');

EmberViewModule.ViewKeywordSupport.apply(MetalView.prototype);
EmberViewModule.ViewStreamSupport.apply(MetalView.prototype);
EmberViewModule.ViewChildViewsSupport.apply(MetalView.prototype);
EmberViewModule.ViewContextSupport.apply(MetalView.prototype);
EmberViewModule.TemplateRenderingSupport.apply(MetalView.prototype);

var Evented = Ember.__loader.require('ember-runtime/mixins/evented')['default'];
Evented.apply(MetalView.prototype);

extend(MetalView, {
  classProps: ['classProps', 'isClass', 'isViewClass', 'isMethod', 'proto', 'create', 'extend', 'reopenClass'],
  isClass: true,
  isViewClass: true,
  isMethod: false,

  proto: function() {
    return MetalView.prototype;
  },

  create: function(props) {
    return new this(props);
  },

  extend: function(props) {
    var ParentClass = this;
    var Subclass = function(props) { ParentClass.call(this, props); };
    Subclass.superclass = ParentClass;
    var classProps = ParentClass.classProps;
    var key;
    for (var i = 0, l = classProps.length; i < l; i++) {
      key = classProps[i];
      Subclass[key] = this[key];
    }
    Subclass.prototype = Ember.create(this.prototype);
    if (props) { extend(Subclass.prototype, props); }
    return Subclass;
  },

  reopenClass: function(props) {
    extend(this, props);
  }
});

export default MetalView;
<|endoftext|>