import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:tangheem/classes/consts.dart';

class BookMarkModel {
  int surahID;
  String surahNameAR;
  int ayahID;
  int numberInSurah;
  int page;
  String ayahText;

  BookMarkModel({this.surahID, this.surahNameAR, this.ayahID, this.numberInSurah, this.page, this.ayahText});

  BookMarkModel.fromJson(Map<String, dynamic> json) {
    surahID = json['surahID'];
    surahNameAR = json['surahNameAR'];
    ayahID = json['ayahID'];
    numberInSurah = json['numberInSurah'];
    page = json['page'];
    ayahText = json['ayah_Text'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['surahID'] = this.surahID;
    data['surahNameAR'] = this.surahNameAR;
    data['ayahID'] = this.ayahID;
    data['numberInSurah'] = this.numberInSurah;
    data['page'] = this.page;
    data['ayah_Text'] = this.ayahText;
    return data;
  }

  String reverseAyatNumber() {
    String _ayaTemp = ayahText.substring(0, ayahText.length - numberInSurah.toString().length);
    String _ayaNum = ayahText.substring(ayahText.length - numberInSurah.toString().length, ayahText.length);
    _ayaNum = _ayaNum.split('').reversed.join('');
    return "$_ayaTemp$_ayaNum";
  }

  static Future<List<BookMarkModel>> getFromPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List encodedList = prefs.getStringList(GlobalConsts.bookmark) ?? [];
    return encodedList.map((e) => BookMarkModel.fromJson(jsonDecode(e))).toList();
  }

  static void saveToPrefs(List<BookMarkModel> list) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    List encodedList = list.map((e) => jsonEncode(e.toJson())).toList();
    await prefs.setStringList(GlobalConsts.bookmark, encodedList);
  }
}
