m3l7
8/17/2014 - 9:10 PM

ztrapi2.js

angular.module('ztrapi', [
  'ngResource'
])
.factory('api',function($resource){
  
  var service = {
    user: $resource('/apiv1/user/:uid', {uid:'@id'}),
    docs: $resource('/apiv1/user/:uid/docs', {uid:'@id'}),
    doc: $resource('/apiv1/user/:uid/docs/:docid', {uid:'@id',docid:'@docid'},{ query: { isArray: false }}),
    docinfo: $resource('/apiv1/user/:uid/docs/:docid/info', {uid:'@id',docid:'@docid'}),
    newword: $resource('/apiv1/user/:uid/docs/:docid/newword', {uid:'@uid',docid:'@docid'}),
    dicts: $resource('/apiv1/user/:uid/dicts', {uid:'@uid'}),
    dict: $resource('/apiv1/user/:uid/dicts/:did', {uid:'@uid',did:'@did'}),
    register: $resource('/register',{}),
    activate: $resource('/activate/:activationCode',{activationCode:'@activationCode'}),

    tag: $resource('/apiv1/user/:uid/tags/:tagname', {uid:'@id',tagname:'@tagname'}),
    upload_dict_action: function(uid,name){return "/apiv1/user/"+uid+"/dicts?name="+name},
    import_doc_action: function(uid,name){
      if (name==undefined) return "/apiv1/user/"+uid+"/docs"
      else return "/apiv1/user/"+uid+"/docs?name="+name
    }
  }
  
  return service
})


angular.module('ztrapi_data',['ngResource', 'ztrapi','settings'])
.factory('data',function($resource,api,settings){
  var service = {
    tags: [],
    docs: [],
    languages: [],
    docinfo: '',
    doccontent: [],
    doccontent_screen: [],
    newwords_matrix: [],
    dicts: [],
    
    //doc height settings
    lineOffset: 0,
    first_line_offscreen: 0,
    first_line_onscreen: 0,
    isPrevPage: false,
    line_per_page: settings.line_per_page,
    page_info: [],
    page:0,
    endOfDoc: false,

    build_screen_doccontent: function(){
      service.doccontent_screen = []
      service.endOfDoc = false
      for (var i = 0; i < service.line_per_page; i++) {
        var line = service.doccontent[service.lineOffset+i]
        if (!!line) 
          service.doccontent_screen.push(line)
        else {
          service.endOfDoc = true
          break
        }
      };
    },
    remove_line_screen_doccontent: function(line_id){
      var contentLength = service.doccontent_screen.length
      for (var i = contentLength - 1; i >= 0; i--) {
        if (service.doccontent_screen[i].line==line_id) {
          service.doccontent_screen.splice(i,contentLength-i)
          break
        }
      };
    },

    
    get_docs: function(uid,next){
      service.docs = []
      api.docs.query({uid:uid},function(docs){
      	service.docs = docs
      	var tags = []
      	for (i=0;i<docs.length;i++){
      	  for (j=0;j<docs[i].metadata.tags.length;j++){
            var add=true
            for (var k = tags.length - 1; k >= 0; k--) {
              if (tags[k].text==docs[i].metadata.tags[j].text){
                add=false
                break
              }
            };
            if (add) tags.push(docs[i].metadata.tags[j])
      	  }
      	}
      	service.tags = tags

        // FILL LANG LIST
      	var langs = []
        var langs_id = []
      	for (i=0;i<docs.length;i++){
      	  var l = docs[i].metadata.lang_from
      	  if ((l.id!='') && (langs_id.indexOf(l.id)==-1)) {
            langs.push(l)
            langs_id.push(l.id)
          }
      	}
      	service.languages = langs
      	if (next!=undefined) next()
            })
    },
    save_doc_info: function(uid,docid,next){
      service.docinfo.$save({uid:uid,docid:docid})
    },
    get_doc_info: function(uid,docid,next){
      service.docinfo = []
      var docinfo_id = JSON.parse(localStorage['docinfo_id'])
      var docinfo = JSON.parse(localStorage['docinfo'])
      
      var i
      if ((i=docinfo_id.indexOf(docid))>-1){
        	service.docinfo = docinfo[i]
      }
      api.docinfo.query({uid:uid,docid:docid},function(d){
        	service.docinfo = d[0]

        	if (i>-1){
        	  docinfo_id.splice(i,1)
        	  docinfo.splice(i,1)
        	}
        	
        	docinfo_id.push(docid)
        	docinfo.push(d[0])
        	var cache = [];
        	localStorage['docinfo_id']=JSON.stringify(docinfo_id)
        	localStorage['docinfo']=JSON.stringify(docinfo, function(key, value) {
        	  if (typeof value === 'object' && value !== null) {
        	    if (cache.indexOf(value) !== -1)  return;
        	    cache.push(value);
        	  }
        	  return value;
        	})
        	cache = null; // Enable garbage collection
        	if (next!=undefined) next()
      })
    },
    delete_doc: function(uid,docid,next){
      var doccontent_id = JSON.parse(localStorage['doccontent_id'])
      var docinfo_id = JSON.parse(localStorage['docinfo_id'])
      
      if ((i=doccontent_id.indexOf(docid))>-1){
        	var doccontent = JSON.parse(localStorage['doccontent'])
        	doccontent.splice(i,1)
        	doccontent_id.splice(i,1)
        	localStorage['doccontent_id']=JSON.stringify(doccontent_id)
        	localStorage['doccontent']=JSON.stringify(doccontent)
      }
      if ((i=docinfo_id.indexOf(docid))>-1){
        	var docinfo = JSON.parse(localStorage['doccontent'])
        	docinfo.splice(i,1)
        	docinfo_id.splice(i,1)
        	localStorage['docinfo_id']=JSON.stringify(docinfo_id)
        	localStorage['docinfo']=JSON.stringify(docinfo)
      }
	
      api.doc.delete({uid:uid,docid:docid},function(docs){
	         if (next!=undefined) next()
      })
    },
    build_doc_from_localstorage: function(docid){
      var doccontent_id = JSON.parse(localStorage['doccontent_id'])
      var doccontent = JSON.parse(localStorage['doccontent'])
      if ((i=doccontent_id.indexOf(docid))>-1){
        i=doccontent_id.indexOf(docid)
        // service.doccontent = doccontent[i].split('\n')
        service.doccontent = doccontent[i]
        return true
      }
      else return false
    },
    save_doc_to_localstorage: function(docid){
      var doccontent_id = JSON.parse(localStorage['doccontent_id'])
      var doccontent = JSON.parse(localStorage['doccontent'])
      ls_id = doccontent_id.indexOf(docid)
      doccontent[ls_id] = service.doccontent
      localStorage['doccontent_id']=JSON.stringify(doccontent_id)
      localStorage['doccontent']=JSON.stringify(doccontent)
    },
    get_doc: function(uid,docid,next){
      //WARNING: LOAD ALWAYS AFTER DOCINFO!!!!!
      service.doccontent=''
      
      var doccontent_id = JSON.parse(localStorage['doccontent_id'])
      var doccontent = JSON.parse(localStorage['doccontent'])
      if (!service.build_doc_from_localstorage(docid)) {
        //the file is not in localstorage, let's fetch it from server
        api.doc.query({uid:uid,docid:docid},function(ret){
	       var d=''
         for (var i in ret){
          if (!isNaN(parseInt(i))) d+=ret[i]
         }

          var splitted = d.split('\n')
          service.doccontent = []
          for (var i = 0; i < splitted.length; i++) {
            service.doccontent.push({
              words: [],
              line: i
            })
            splittedwords = splitted[i].split(" ")

            for (var j = 0; j < splittedwords.length; j++) {
              //check if the word is new and add it to service

              var newword = false
              for (var k = 0; k < service.docinfo.metadata.newwords.length; k++) {
                var nw = service.docinfo.metadata.newwords[k]
                if ((i==nw.line) && (nw.fword<=j) && (nw.lword>=j)) newword = true
              };

              service.doccontent[i].words.push({
                text: splittedwords[j],
                word: j,
                newword: newword
              })
            };
          };
          doccontent_id.push(docid)
          doccontent.push(service.doccontent)
          localStorage['doccontent_id']=JSON.stringify(doccontent_id)
          localStorage['doccontent']=JSON.stringify(doccontent)
	         if (next!=undefined) next()
        })
      }
      else if (!!next) next()
    },
    save_word: function(uid,docid,line,fword,lword,text,context,origText,transText,update,next){
      api.newword.save({uid:uid,docid:docid,line:line,text:text,fword:fword,lword:lword,context:context,transText:transText,origText:origText,update:update})
      if (!update) service.docinfo.metadata.newwords.push({
        line: line,
        fword: fword,
        lword: lword,
        text: text,
        origText: origText,
        transText: transText,
        context: context
      })
      else{
        var nw = service.docinfo.metadata.newwords
        for (var i = 0; i < nw.length; i++) {
          if ((line==nw[i].line) && (fword==nw[i].fword)){
            //update word client-side
            service.docinfo.metadata.newwords[i].line = line
            service.docinfo.metadata.newwords[i].fword = fword
            service.docinfo.metadata.newwords[i].lword = lword
            service.docinfo.metadata.newwords[i].text = text
            service.docinfo.metadata.newwords[i].origText = origText
            service.docinfo.metadata.newwords[i].transText = transText
            service.docinfo.metadata.newwords[i].context = context
          }
        };

      }

      for (var i = fword; i <= lword; i++) {
        service.doccontent[line].words[i].newword = true
      };
      service.save_doc_to_localstorage(docid)
    },

    remove_new_word: function(uid,docid,line,fword,lword,next){
      api.newword.remove({uid:uid,docid:docid,line:line,fword:fword,lword:lword})
      // debugger
      var newwords = service.docinfo.metadata.newwords
      for (var i = newwords.length-1; i >= 0; i--) {
        var del = false
        if ((newwords[i].line==line) && (newwords[i].fword<=fword) && (newwords[i].lword>=fword)) del = true
        else if ((newwords[i].line==line) && (newwords[i].fword>=fword) && (newwords[i].fword<=lword)) del = true
        if (del){
          var fwl = service.docinfo.metadata.newwords[i].fword
          var lwl = service.docinfo.metadata.newwords[i].lword
          for (var j = fwl; j <= lwl; j++) {
            service.doccontent[line].words[j].newword = false  
          };
          service.docinfo.metadata.newwords.splice(i,1)
        } 
      };

      service.save_doc_to_localstorage(docid)
    },
    get_word_from_line_fword: function(line,fword){
      var nw = service.docinfo.metadata.newwords
      for (var i = 0; i < nw.length; i++) {
        if ((line==nw[i].line) && (fword==nw[i].fword)) return nw[i]
      };
      return {}
    },
    get_dict_list: function(uid,next){
      api.dicts.query({uid:uid},function(ret){
        service.dicts = ret
        if (next!=undefined) next()
      })
    },
    delete_dict: function(uid,did,next){
      api.dict.delete({uid:uid,did:did},function(err,ret){
          for (var i = 0; i < service.dicts.length; i++) {
            if (service.dicts[i]._id==did){
              service.dicts.splice(i,1)
            }
          };
        if (next!=undefined) next()
      })
    },
    register: function(user,email,pass,next){
      api.register.save({user:user,pass:pass,email:email})
      .$promise.then(function(){
        if (!!next) next()
      },function(err){
        if (!!next) next(err.data)
      })
    },
    activateUser: function(activationCode,next){
      api.activate.save({activationCode:activationCode})
      .$promise.then(function(){
        console.log('asdaaa')
        if (!!next) next()
      },function(err){
        console.log('asd')
        if (!!next) next(err.data)
      })
    }
  }
  return service
})