import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import {
  Http,
  Headers,
  RequestOptions,
} from '@angular/http';
import { CryptoService } from '../crypto/crypto.service';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class ChattingService {
  baseurl = environment.baseurl;
  AdminauthToken: any;
  AdminId: any;
  constructor(public http: Http, public HttpClient: HttpClient, private crypto: CryptoService) { }
  saveMessage(cohort_id, user_id, message_type, message, channel_arn, message_id, reply_user_id, reply_user_name, reply_user_avatar, reply_message, image, read_by, ref_number, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        cohort_id: cohort_id,
        user_id: user_id,
        message_type: message_type,
        message: message,
        channel_arn: channel_arn,
        message_id: message_id,
        reply_user_id: reply_user_id,
        reply_user_name: reply_user_name,
        reply_message: reply_message,
        image: image,
        read_by: read_by,
        reply_user_avatar: reply_user_avatar,
        ref_number: ref_number
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.ADD_MESSAGE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  getAllChannel(user_id, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        user_id: user_id
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.ALL_CHANNEL;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  getAllChannelUsers(Ids, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        Ids: Ids
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.CHANNEL_USERS;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  getMessage(cohort_id, limitRecord, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        cohort_id: cohort_id,
        limitRecord: limitRecord
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.GET_MESSAGE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  emojiUpdate(updateEmoji, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify(updateEmoji))
    }
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.EMOJI_UPDATE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  getSingleMessage(cohort_id, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        cohort_id: cohort_id
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.GET_SINGLE_MESSAGE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  async addNotification(notification, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        "data": notification,
        "table": "Notifications"
      }))
    }
    return new Promise(resolve => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);
      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.ADD_NOTIFICATION
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res["_body"] }])
        },
        (err) => {
          resolve([{ status: err.status, json: err["_body"] }])
        }
      );
    });
  }
  deleteMessage(id, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        id: id
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.DELETE_MESSAGE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  markAsRead(id, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        id: id
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.MARK_AS_READ;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }


  //conference
  getConferenceMessage(meeting_id, limitRecord, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        meeting_id: meeting_id,
        limitRecord: limitRecord
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.GET_MESSAGE_CONFERENCE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  saveMessageConference(cohort_id, user_id, meeting_id, aws_meeting_id, message_type, attendees_log, message, ref_number, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        cohort_id: cohort_id,
        user_id: user_id,
        meeting_id: meeting_id,
        aws_meeting_id: aws_meeting_id,
        message_type: message_type,
        attendees_log: attendees_log,
        message: message,
        ref_number: ref_number
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.ADD_MESSAGE_CONFERENCE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  getSingleMessageConference(meeting_id, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        meeting_id: meeting_id
      }))
    };
    return new Promise((resolve) => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);

      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.GET_SINGLE_MESSAGE_CONFERENCE;
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res['_body'] }]);
        },
        (err) => {
          resolve([{ status: err.status, json: err['_body'] }]);
        }
      );
    });
  }
  async getMeetingById(id, token) {
    var data = {
      data: this.crypto.encrypt(JSON.stringify({
        "id": id
      }))
    }
    return new Promise(resolve => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);
      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.LIVE_EVENT_BYID
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res["_body"] }])
        },
        (err) => {
          resolve([{ status: err.status, json: err["_body"] }])
        }
      );
    });
  }
  async uploadFile_OLD(base64Data, mime, token) {
    var data = {
      "base64Data": base64Data,
      "mime_type": mime
    }
    return new Promise(resolve => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);
      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.UPLOAD_FILE
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res["_body"] }])
        },
        (err) => {
          resolve([{ status: err.status, json: err["_body"] }])
        }
      );
    });
  }
  async uploadFile(base64Data, mime_type, file_type, token) {
    var complete_data = {
      file_type: file_type,
      base64Data: base64Data
    }

    return new Promise(resolve => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);
      let options = new RequestOptions({ headers: headers });
      var url = "https://teach.dstncert.com/chime/upload_file.php"
      this.http.post(url, complete_data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res["_body"] }])
        },
        (err) => {
          resolve([{ status: err.status, json: err["_body"] }])
        }
      );
    });

  }
  async uploadLargePart(uploadPromiseResult, token) {

    var data = {
      "upload_data": uploadPromiseResult.upload_data,
      "upload_key": uploadPromiseResult.upload_key
    }
    return new Promise(resolve => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer ' + token);
      let options = new RequestOptions({ headers: headers });
      var url = this.baseurl + environment.UPLOAD_LARGE_FILE
      this.http.post(url, data, options).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res["_body"] }])
        },
        (err) => {
          resolve([{ status: err.status, json: err["_body"] }])
        }
      );
    });
  }
  async Rclogin(name: string, pass: string): Promise<Observable<any>> {
    return this.http.post(`http://64.23.254.43:3100/api/v1/login`, {
      username: name,
      password: pass
    });
  }
  RccreateUser(authToken: string, userId: string, username: string, password: string, email: string, name: string): Observable<any> {
    let headers = new Headers();
    headers.append('X-Auth-Token',  authToken);
    headers.append('X-User-Id', userId);

    return this.http.post(`http://localhost:3000/api/v1/users.create`, {
      username,
      password,
      email,
      name,
      roles: ['user']
    }, { headers });
  }

  RcaddUserToGroup(authToken: string, AdminuserId: string, userId: string, groupId: string, username: string): Observable<any> {
    const headers = new HttpHeaders({
      'X-Auth-Token': authToken,
      'X-User-Id': userId
    });

    // let headers = new Headers();
    // headers.append('X-Auth-Token',  authToken);
    // headers.append('X-User-Id', AdminuserId);

    return this.HttpClient.post(`http://localhost:3000/api/v1/groups.invite`, {
      roomId: groupId,
      userId: userId
    }, { headers });
  }

  RclistGroups(authToken: string, userId: string): Observable<any> {
    let headers = new Headers();
    headers.append('X-Auth-Token',  authToken);
    headers.append('X-User-Id', userId);

    return this.http.get(`http://localhost:3000/api/v1/groups.list`, { headers });
  }

  async RcloginAdmin(username: string, password: string): Promise<void> {
    const data = {
      "username": username,
      "password": password
    };

    const response: any = await this.http.post(`http://64.23.254.43:3100/api/v1/login`, data).toPromise();
    if (response.status == 200) {
      let data = JSON.parse(response["_body"]).data
      this.AdminauthToken = data.authToken;
      this.AdminId = data.userId;
    } else {
      throw new Error('Authentication failed');
    }
  }

  async RcsetAvatar(Uavatar, Uid){
    if(!this.AdminauthToken){
      await this.RcloginAdmin("flexxon", "Newpassword02#");
    }
    var data = JSON.stringify({
      "avatarUrl": Uavatar,
      "userId": Uid,
    })
    return new Promise(resolve => {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Content-Type', 'application/json');
      headers.append("X-Auth-Token", this.AdminauthToken);
      headers.append("X-User-Id", this.AdminId);
      let options = new RequestOptions({ headers: headers });
      var url = "http://64.23.254.43:3100/api/v1/users.setAvatar";
      this.http.post(url, data, options ).subscribe(
        (res) => {
          resolve([{ status: res.status, json: res["_body"] }])
        },
        (err) => {
          resolve([{ status: err.status, json: err["_body"] }]);
          console.log(err)
        }
      );
    });
  }
}
