var logger     = require('../util/logger');
var common     = require('../util/common');
var config     = require('../../wb.config');
var constants  = require('../constants');
var queries    = require('./queries');
var errors     = require('../errors');

var PageResAM = function(dbc)
{
  this.dbc = dbc;
}

PageResAM.prototype.create = function(pageres,_callback)
{
  logger.debug('create page resource'+JSON.stringify(pageres));

  var query=queries.pageres.create;
  var dbc=this.dbc;

  var chain = common.chain().start()
                            .add(dbc,dbc.beginTransaction)
                            .add(dbc,dbc.query,query,[pageres.pageOid, pageres.aid])
                            .add(dbc,dbc.commit)
                            .invoke(function(err)
                            {
                              _callback(errors.create('DB_INSERT_ERROR','Error while creating page resource',err));
                              return false;
                            },
                            function()
                            {
                              _callback(null,pageres);
                            });
}


PageResAM.prototype.deleteList = function(request,_callback)
{
  logger.info('delete page resources '+JSON.stringify(request));
  var dbc=this.dbc;
  
  var chain = common.chain().start().add(dbc,dbc.beginTransaction);
  for(var i=0,l=request.list.length;i<l;i++)
  {
    var item=request.list[i];
    chain.add(dbc,dbc.query,queries.pageres.deleteList,[item.pageOid,item.aid])
  }
  chain.add(dbc,dbc.commit);
  chain.invoke(function(err)
               {
                 _callback(errors.create('DB_DELETE_ERROR','Error while deleting page resources ',err));
                 return false;
               },
               function()
               {
                 _callback(null,request);
               });
 }


module.exports=function(dbc)
{
  return new PageResAM(dbc);
};


