import { Component,ViewChild,ElementRef} from '@angular/core';
import {IonicPage,NavController,ViewController,NavParams,Platform} from 'ionic-angular';
import { Content } from 'ionic-angular';
import {FirebaseService} from '../../providers/firebase.service';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import {Validators, FormBuilder, FormGroup } from '@angular/forms';
import * as firebase from 'firebase';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { Geolocation } from '@ionic-native/geolocation';
import {Myservice} from '../../providers/myservice';

@IonicPage()
@Component({
  selector: 'page-chat',
  templateUrl: 'chat.html'
})
export class Chat {
  @ViewChild(Content) content: Content;
   private chatform : FormGroup;
 // @ViewChild('scrollMe') private myScrollContainer: ElementRef;
data:any;
id1:any;
id2:any;
length:any;
final:any;
messages:any;
lastmessagekey:any;
msg:any;
userdata:any;
first_name:any;
locationmsg:any;
location:any;
scrolledmsg:any;
msg_show:any;
chatuser:any;
cot:any;
unread:any;
msg_item:any;

  constructor(public navCtrl: NavController,public viewCtrl: ViewController,private formBuilder: FormBuilder,
  private iab: InAppBrowser,public navParams: NavParams,public firebaseService:FirebaseService,public myservice:Myservice,
  private platform: Platform, private geolocation: Geolocation) {
     this.data= navParams.get("data");
     console.log(this.data.To_id);
    //  this.chatdata= navParams.get("chatdata");
    this.userdata= navParams.get("userdata");
    this.first_name =this.userdata.first_name;
     this.chatform = this.formBuilder.group({ 
      msg: ['', Validators.required],

     
    });
     this.myservice.load_post(this.data.To_id,"chatuserdetails").subscribe(response => {
         console.log(response.data);
         this.chatuser=response.data;

      console.log(response);
    })
    if(this.data){
       this.id1 = this.data.From_id;
       console.log(this.id1);
       this.id2 = this.data.To_id;
      // console.log(this.id2);
    }
    
       console.log(this.data);
       this.msg_show =true;
       this.loadmsg();
       this.unread_msg();
                platform.ready().then(() => {
             var This=this;
      geolocation.getCurrentPosition().then((location) => {
      
        console.log(location);
      
        This.location=location;
         console.log(this.location.coords.latitude);

        
      }).catch((error) => {
      
        console.log('Error getting location', error);
        
      });
       this.location=This.location;
      
    } );
       


  }
  unread_msg(){
      var updateurll = "msg_unread/" + this.id1 + "/" + this.id2 + "/";
        this.firebaseService.checkItem(updateurll).subscribe((item) => {
            console.log('item',item)
              console.log('item',item.$value)
               console.log('item',item.count)
               this.msg_item=item.count;
        })
      

  }
  loadmsg(){
  
      console.log(this.data);
      console.log(this.id1) ;   
       console.log(this.id2) ;
                      //load last 10 messages initially//
if (this.id1 < this.id2) {

            //console.log(this.id1);
            var url = "chats/" + this.id1 +'-'+ this.id2 + "/";
            var query = {
                query: {
                    limitToLast: 10
                }
            };

            this.length = this.firebaseService.listItem(url).subscribe((item) => {
                console.log('len',item.length);
                this.length = item.length;
            });
            this.data = this.firebaseService.listItemQuery(url, query);

            this.data.subscribe((user) => {
                //console.log(typeof(this.message));
                 this.final = user;
                 if (user.length != 0) {
                 this.messages = user;
                console.log('final',this.final);
                // console.log(this.message);
                this.lastmessagekey = user[0].$key;
                 }
            })
        } else {
            var url = "chats/" + this.id2 +'-'+ this.id1 + "/";

            var query = {
                query: {
                    limitToLast: 10
                }
            };

            this.firebaseService.listItem(url).subscribe((item) => {
                console.log(item.length);
                this.length = item.length;
            });
            console.log(this.length);
            this.data = this.firebaseService.listItemQuery(url, query);

            console.log(this.data);


            this.data.subscribe((user) => {
                console.log(user);
                this.final = user;
                    if(user.length!=0){
                this.messages = user;
                this.lastmessagekey = user[0].$key;
                console.log(this.lastmessagekey);
                }

            })

        }

  }
    ionViewDidEnter() {
        //  alert(2)

        this.content.scrollToBottom(0);
    }
  

  ionViewDidLoad() {
    console.log('Hello Chat Page');
  }
  send(post){
    this.msg=post.msg;
      var msg = {
        "From_id": this.id1,
        "To_id": this.id2,
        "message": this.msg,
        "timestamp": firebase.database.ServerValue.TIMESTAMP,
        "type":'text'  
      }
    
      this.chatform.reset()

        console.log(msg);

        if (this.id1 < this.id2) {

        var url = "chats/" + this.id1 +'-'+ this.id2 + "/";
        this.firebaseService.pushItem(url, msg);
      
         var recenturl="recentmsg/"+ this.id1+'/' +this.id1 +'-'+ this.id2 + "/";
          this.firebaseService.createItem(recenturl, msg);
          var recenturl="recentmsg/"+ this.id2+'/' +this.id1 +'-'+ this.id2 + "/";
          this.firebaseService.createItem(recenturl, msg);
            this.msg=''

        } else {
        var url = "chats/" + this.id2 +'-'+ this.id1 + "/";
        
        this.firebaseService.pushItem(url, msg);
         var recenturl="recentmsg/"+ this.id1+'/' +this.id2 +'-'+ this.id1 + "/";
          this.firebaseService.createItem(recenturl, msg);
         var recenturl="recentmsg/"+ this.id2+'/' +this.id2 +'-'+ this.id1 + "/";
          this.firebaseService.createItem(recenturl, msg);
           this.msg=''
      }
       var upurl = "msg_unread/" + this.id1 +"/"+ this.id2 + "/";
    //    alert(this.unread);
    //    console.log(this.unread); undefined
    console.log(this.msg_item );
     if (this.msg_item == undefined) {
        //  alert('ys0')
           
                   var count_msg={"count":1}
            

            this.firebaseService.createItem(upurl,count_msg);

        } else {
            // alert((this.msg_item));
            //  alert(Number(this.msg_item) + 1);
              var count1_msg={"count":this.msg_item + 1}



            this.firebaseService.createItem(upurl,count1_msg);
        }
       
 
  }
   locationselect(){

 
    this.locationmsg={'lattitude':this.location.coords.latitude,'longitude':this.location.coords.longitude}
      var msg= {"From_id": this.id1,
        "To_id": this.id2,
        "message": this.locationmsg,
        "timestamp": firebase.database.ServerValue.TIMESTAMP,
        "type":'location'}
     
        if (this.id1 < this.id2) {

        var url = "chats/" + this.id1+'-'+this.id2 + "/";

        this.firebaseService.pushItem(url, msg);
          var recenturl="recentmsg/"+ this.id1+'/' +this.id1 +'-'+ this.id2 + "/";
          this.firebaseService.createItem(recenturl, msg);
          var recenturl="recentmsg/"+ this.id2+'/' +this.id1 +'-'+ this.id2 + "/";
          this.firebaseService.createItem(recenturl, msg);
            this.msg=''
        
      
    } else {
        var url = "chats/" + this.id2 +'-'+ this.id1 + "/"; 
        this.firebaseService.pushItem(url, msg);
        var recenturl="recentmsg/"+ this.id1+'/' +this.id2 +'-'+ this.id1 + "/";
         this.firebaseService.createItem(recenturl, msg);
         var recenturl="recentmsg/"+ this.id2+'/' +this.id2 +'-'+ this.id1 + "/";
          this.firebaseService.createItem(recenturl, msg);
        this.msg=''
      }
        var loc_upurl = "msg_unread/" + this.id1 +"/"+ this.id2 + "/";
        if (this.msg_item == undefined) {
        //  alert('ys0')
           
                   var count_msg={"count":1}
            

            this.firebaseService.createItem(loc_upurl,count_msg);

        } else {
            // alert((this.msg_item));
            //  alert(Number(this.msg_item) + 1);
              var count1_msg={"count":this.msg_item + 1}



            this.firebaseService.createItem(loc_upurl,count1_msg);
        }
 
  }
  dismiss() {
   this.viewCtrl.dismiss();
 }
openLink(lattitude,longitude){
    var link='https://google.com/maps/?q=' +lattitude +',' +longitude;
    const ref  = this.iab.create(link,'_self',{location:'yes'}); 

}
 doInfinite(refresher) {
     
     console.log("scrolled");
     this.scrolledmsg = this.final;
     console.log(this.scrolledmsg.length);
      console.log(this.length);
      
        if (this.length >= this.scrolledmsg.length) {
                this.final = [];
                var length = this.messages.length;
                 var lastkey = this.lastmessagekey;
                  if (this.id1 < this.id2) {
                         var url = "chats/" + this.id1 +'-'+ this.id2 + "/";
              var query = {
                  query: {

                      orderByKey: 'timestamp',
                      endAt: lastkey,
                      limitToLast: 10
                  }
              };
                this.data = this.firebaseService.listItemQuery(url, query);

              this.data.subscribe((user) => {
                  this.lastmessagekey = user[0].$key;
                  this.final = user;
                  console.log (this.lastmessagekey);
                  this.scrolledmsg.forEach(item => {
                      this.final.push(item);
                      console.log(this.final.length);
                      console.log('srol',this.final);
                  });

              })


                  }else {
              var url = "chats/" + this.id2 +'-'+ this.id1 + "/";

              console.log("case:false");

              var query = {
                  query: {
                      orderByKey: 'timestamp',
                      endAt: lastkey,
                      limitToLast: 10
                  }
              };
              this.data = this.firebaseService.listItemQuery(url, query);


              this.data.subscribe((user) => {

                  this.lastmessagekey = user[0].$key;
                  this.final = user;
                //   console.log(this.message);
                  this.scrolledmsg.forEach(item => {
                      this.final.push(item);

                      console.log(this.final);
                  });

              })

          }
          setTimeout(() => {
            refresher.complete();
             }, 2000);

        }else{ 
                 console.log('Async operation has ended');
               this.msg_show =false;
                      refresher.complete();
   
    //  
    
        }
 
    //
  }

// scrollToBottom(): void {
//         try {
//             this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
//         } catch(err) { }                 
//     }


 

}