import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, HelpBlock , Alert , Button , Well , 
    Jumbotron ,Table , Label , ButtonGroup} from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { GetNameFromUserId , Capitalize ,
         sumMeUp , getCommision , getPaymentType }
    from '../../../modules/utilities';
import Loading from '../../components/Loading/Loading';
import Transactions from '../../../api/Transactions/Transactions';
import Papers from '../../../api/Papers/Papers';
import Journal from '../../../api/Journal/Journal';
import {_} from 'meteor/underscore';
import { ReactiveVar } from 'meteor/reactive-var';
import moment from 'moment';
import TransactionComponent from '../../components/Transaction/Transaction';
    


    class AdminTransactionPage extends React.Component {
      constructor(props){
          super(props)
          this.state = {
             
          }
        this.handleFilterStatus = this.handleFilterStatus.bind( this );
      }
  
      handleFilterStatus( event ){
        const paymentType = this.paymentType.value;
        const paymentYear = this.paymentYear.value;
        const journal = this.journal.value;
        let filter = {}
        if ( paymentType != "0"){
              filter.paymentType = paymentType;
        }
        if ( paymentYear != "0"){
            filter.paymentYear = paymentYear
        }
        if ( journal != "0") {
          filter.journalId = journal;
        }
        const {QueryFilter} = this.props;
        QueryFilter.set(filter);
      }
  
      render() {
          const {loading , transactions , QueryFilter , journal } = this.props;
          let total=0;
          return (!loading ? (
                <div>
                  <Row>
                    <Col md={10} mdOffset={1}>
                      <Well>
                      <Row>
                      <Col md={4}>
                          <p>Journal </p>
                            <select ref={journal => (this.journal = journal )} 
                              className="form-control">
                                <option value="0">select journal</option>
                                {journal && journal.map(({journalName , _id } , index)=>{
                                  return (
                                    <option key={index} value={_id}>{journalName}</option>
                                  )
                                })}
                            </select>
                         </Col>

                        <Col md={4}>
                          <p>Payment type </p>
                            <select ref={paymentType => (this.paymentType = paymentType )} 
                              className="form-control">
                                <option value="0">select payment type</option>
                                <option value="0">all payment</option>
                                <option value="01">payment for review</option>
                                <option value="02">payment for publication</option>
                                <option value="03">payment for journal creation</option>
                            </select>
                         </Col>

                         <Col md={4}>
                          <p> Transaction Year </p>
                          
                            <select ref={paymentYear => (this.paymentYear = paymentYear )}
                                className="form-control">
                                <option value="0">select payment type</option>
                                <option value="2017">2017</option>
                                <option value="2018">2018</option>
                            </select>
                         </Col>
                        
                       <Row>
                       <br/>
                        <br/>
                        <div className="text-center filterButton">
                            <Button bsStyle="success"
                             onClick={this.handleFilterStatus} 
                             bsSize="small"
                            >Filter Payment
                            </Button>
                         </div>
                      </Row>
                    </Row>
                  </Well>
                </Col>
              </Row>
          <TransactionComponent loading={loading} transactions={transactions} />
      </div>
    ) : <Loading/> )
  }
}

    AdminTransactionPage.propTypes = {
      loading: PropTypes.bool.isRequired,
      transactions : PropTypes.arrayOf(PropTypes.object).isRequired,
    };

    let QueryFilter = new ReactiveVar({});
    
    export default createContainer(({ }) => {
      const subscription = Meteor.subscribe('transaction.getAllTransactions');
      let transactions;
      let papers;
      let transactionsPapers = [];
      let paperFilter = {}
      if ( subscription.ready()){
        let filter = QueryFilter.get();
    
        if ( filter.paymentYear ) {
            const {paymentYear} = filter
            const startDate = `${paymentYear}-01-01T00:00:00.000Z`;
            const endDate = `${paymentYear}-12-31T00:00:00.000Z`
            filter.date =  {
              $gte: (startDate),
              $lte: (endDate)
            }
            delete filter.paymentYear;
        }

        if ( filter.journalId ){
           paperFilter.journalID = filter.journalId
        }
             //add the journalid to the filter
            transactions = Transactions.find(filter, {sort : {"date" : -1 }}).fetch();
            papers = Papers.find( paperFilter ).fetch();
            //loop through the transactions and attach the paper title.
            transactions.map((transaction , index )=>{
              const transObj = transaction;
              if ( transObj.paperId ){
                const paper = _.find( papers , (paperToFind)=> {
                    return paperToFind._id == transObj.paperId;
                });
                //get the journal the paper is attached to
                const journal = Journal.find( paper && paper.journalID).fetch()
                transObj.paper = paper;
                transObj.journal = journal && journal[0];
                transactionsPapers.push( transObj );
              }
              else{
                transactionsPapers.push( transObj )
              }
            });
      }
      return {
        loading : !subscription.ready(),
        transactions : transactionsPapers,
        journal : Journal.find({}).fetch(),
        QueryFilter ,
      };
    },  AdminTransactionPage );
    
