//
//  CustomizeFieldViewController.m
//  Apex Mobile
//
//  Created by Ray on 14-3-12.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//
 
#import "CustomizeFieldViewController.h"

@interface CustomizeFieldViewController ()

@end

@implementation CustomizeFieldViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)loadFields
{
    //    self.tableView.editing = true;
    self.displayfields = [[NSMutableArray alloc] init];
    self.hidefields = [[NSMutableArray alloc] init];
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    //    NSString* required_ver=[objheader objectForKey:@"client_ver"] ;
    //
    //    appDelegate.sessionid = [objheader valueForKey:@"sessionid"];
    //    appDelegate.user = user;
    //    appDelegate.password = password;
    
    sqlite3 *db =[ApexMobileDB get_db];
    NSString *quary = [NSString stringWithFormat:@"select aname,show from fields_info where function_name='%@' and user='%@' and behavior=%d order by priority,aname",self.function_name, appDelegate.user,self.behavior];
    
    
    
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(db, [quary UTF8String], -1, &stmt, nil) == SQLITE_OK) {
          DebugLog(@"sql:%@",quary);
        while (sqlite3_step(stmt)==SQLITE_ROW)
        {
            NSString *aname = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
            int show = sqlite3_column_int(stmt, 1);
            if(show==1)
                [self.displayfields addObject:aname];
            else
                [self.hidefields addObject:aname];
            
            
        }
        
        sqlite3_finalize(stmt);
    }
    //用完了一定记得关闭，释放内存
    sqlite3_close(db);
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
- (IBAction)onSaveClick:(UIBarButtonItem *)sender {
    if(self.displayfields.count<1)
        
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"alert_title_error", nil) message:NSLocalizedString(@"alert_msg_customizefield", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil];
        //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
        [alert show];
        return;
        
    }
    sqlite3 *db =[ApexMobileDB get_db];
    @try{
        
        
        char *errorMsg;
        ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        if (sqlite3_exec(db, "BEGIN", NULL, NULL, &errorMsg)==SQLITE_OK) {
            
              DebugLog(@"begin transaction success");
            
            sqlite3_free(errorMsg);
            
            for(int i=0;i<self.displayfields.count;i++)
            {
                NSString * sql = [NSString stringWithFormat:@"update fields_info set show = 1 , priority = %d where aname = '%@' and  function_name='%@' and user='%@' and behavior=%d",i,self.displayfields[i],self.function_name, appDelegate.user,self.behavior];
                [ApexMobileDB execSql:sql db:db];
            }
            
            for(int i=0;i<self.hidefields.count;i++)
            {
                NSString * sql = [NSString stringWithFormat:@"update fields_info set show = 0  where aname = '%@' and  function_name='%@' and user='%@' and behavior=%d",self.hidefields[i],self.function_name, appDelegate.user,self.behavior];
                [ApexMobileDB execSql:sql db:db];
            }
            
//            self.dirty = @"true";
            [self.navigationController popViewControllerAnimated:true];
//            sqlite3_stmt *statement;
//            
//            if (sqlite3_prepare_v2(db, [@"insert into persons(name) values(?);" UTF8String], -1, &statement,            NULL)==SQLITE_OK) {
//                
//                //绑定参数
//                
//                const char *text=[@”张三” cStringUsingEncoding:NSUTF8StringEncoding];
//                
//                sqlite3_bind_text(statement, index, text, strlen(text), SQLITE_STATIC);
//                
//                
//                
//                if (sqlite3_step(statement)!=SQLITE_DONE) {
//                    
//                    sqlite3_finalize(statement);
//                    
//                }
//                
//            }
//            
//            
//            
            if (sqlite3_exec(db, "COMMIT", NULL, NULL, &errorMsg)==SQLITE_OK) {
                
                  DebugLog(@"commit success");
                
            }
            
            sqlite3_free(errorMsg);
            
        }else{
            
            sqlite3_free(errorMsg);
            
        }
        
    }
    
    @catch(NSException *e){
        
        char *errorMsg;
        
        if (sqlite3_exec(db, "ROLLBACK", NULL, NULL, &errorMsg)==SQLITE_OK) {
            
              DebugLog(@"rollback success");
            
        }
        
        sqlite3_free(errorMsg);
        
    }
    
    @finally{
        sqlite3_close(db);
        
    }
    
    
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadFields];
//        [self.tableView setSectionIndexColor:[UIColor blueColor]];
//    [self.tableView setSectionIndexBackgroundColor:[UIColor blueColor]];
    //self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self.tableView setEditing:true animated:true];
    // Do any additional setup after loading the view.
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    myView.backgroundColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 22)];
    titleLabel.textColor=[UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    if(section==0)
        titleLabel.text=NSLocalizedString(@"display_items", nil);
    else
        titleLabel.text=NSLocalizedString(@"hide_items", nil);
    [titleLabel sizeToFit];
    [myView addSubview:titleLabel];

    return myView;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    if(section==0)
//        return @"Display fields";
//    else
//        return @"Hide fields";
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 2;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
      DebugLog(@"canMoveRowAtIndexPath");

    if([tableView numberOfRowsInSection:indexPath.section]>1)
        return true;
    else
        return false;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    NSMutableArray * from;
    NSMutableArray * to ;
    if(fromIndexPath.section==0)
        from  = self.displayfields;
    else
        from  = self.hidefields;
    if(toIndexPath.section==0)
        to  = self.displayfields;
    else
        to  = self.hidefields;
    id content=from[fromIndexPath.row];
    [from removeObjectAtIndex:fromIndexPath.row];
    [to insertObject:content atIndex:toIndexPath.row];
    
    [tableView reloadData];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0)
        return self.displayfields.count;
    else
        return self.hidefields.count;
    
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果两次点击的时间间隔小于1秒，则断定为双击事件
    
    if(tableView.editing==false)
        return;
    
    
    if([tableView numberOfRowsInSection:indexPath.section]<=1)
        return;
//    int between = 1;
    NSUInteger curr = [[NSDate date] timeIntervalSince1970];
    
    if(indexPath.row==self.lasttap.row&&indexPath.section==self.lasttap.section)
    {
        if (curr-self.taptime<1) {
              DebugLog(@"double click!");
            self.lasttap =nil;
            
            NSMutableArray * from;
            NSMutableArray * to ;
            int section;
            if(indexPath.section==0)
            {
                from  = self.displayfields;
                to = self.hidefields;
                section = 1;
            }
            else
            {
            
                from  = self.hidefields;
                to = self.displayfields;
                section = 0;
            }
            NSIndexPath * toIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
//            NSIndexPath * headerIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
//            NSIndexPath * headerIndexPath1 = toIndexPath;
            
            id content=from[indexPath.row];
            [tableView beginUpdates];
            [from removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

            [to insertObject:content atIndex:0];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:toIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView endUpdates];
            
//            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:headerIndexPath] withRowAnimation:UITableViewRowAnimationFade];
//            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:headerIndexPath1] withRowAnimation:UITableViewRowAnimationFade];
            [tableView reloadData];
            

        }
        self.taptime = curr;
        
        
    }
    else
    {
        self.taptime = curr;
        self.lasttap = indexPath;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      DebugLog(@"cellForRowAtIndexPath");
    
    NSString *CellIdentifier = @"field";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString* aname;
    if(indexPath.section==0)
        aname = self.displayfields[indexPath.row];
    else
        aname = self.hidefields[indexPath.row];
    cell.textLabel.text = aname;
 
    
    return cell;
    
    
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
