//
//  EditModelPriceViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 9/16/15.
//  Copyright (c) 2015 United Software Applications, Inc. All rights reserved.
//

#import "EditModelPriceViewController.h"
#import "RAUtils.h"

#import "iSalesNetwork.h"
#define NUMBERS @"0123456789.\n"
@interface EditModelPriceViewController ()

@end

@implementation EditModelPriceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.editPrice.text = [NSString stringWithFormat:@"%.2f", self.price ];
    
    
    self.editDiscount.text = [NSString stringWithFormat:@"%@", [RAUtils FloatFormat:self.discount] ];
    
    self.labelNewPrice.text = [NSString stringWithFormat:@"%.2f",self.price* (1.0-self.discount/100)];
    
    if(self.hide_discount)
    {
        self.editDiscount.hidden=true;
        self.labelDiscount.hidden=true;
        self.labelCalPrice.text = @"New price:";
        
        
        
    }
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#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.
}
*/
- (IBAction)onCloseClicked:(id)sender {
    [self dismissViewControllerAnimated:NO
                             completion:^{
                                 
                                 
                             }];
}
- (IBAction)onSaveClicked:(id)sender {
    
    
    
    if([self.editDiscount.text floatValue]>100.0)
    {
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @"Discount error" message:@"Discount must less than 100" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//
//        
//        [alert show];
        
        [RAUtils alert_view:@"Fields with * mark cannot be empty." title:@"Some Requried Fields Are Missing."];
        
        self.editDiscount.text=@"0";
        
        return;
    }
    
    
    [self update_newprice];
    
    

    [self dismissViewControllerAnimated:NO
                             completion:^{
                                 if(self.onSetValue)
                                     self.onSetValue( self.price,self.discount);
                                 
                             }];
    /*
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary* cart_json = nil;
        
        if(self.set_watch_list)
            cart_json= [iSalesNetwork portfolio_setPrice:self.cart_id price:self.price discount:self.discount];
        else
            cart_json = [iSalesNetwork cart_setPrice:self.cart_id price:self.price discount:self.discount];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            if([[cart_json valueForKey:@"result"] intValue]==2)
            {
                [self dismissViewControllerAnimated:NO
                                         completion:^{

                                             
                                         }];
            }
            else
            {
                [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Change Price" controller:self] ;
            }
            
            

            
        });
    });
     
     */
}
#pragma mark textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
//    int tag = textField.tag;
//    
//    int len = textField.text.length;
//    
//    if(textField.tag==2&&textField.text.length>=2 && string.length>0)
//        return false;
    
    if(textField.text.length==0 && [string isEqualToString:@"."])
        return false;
        
//    DebugLog(@"text:%@",textField.text);
//    
//    
//    
//    
//    
//    UITableViewCell *cell = (UITableViewCell *) textField.superview.superview;
//    
//    NSIndexPath *   indexPath = [self.editorTable indexPathForCell:cell];
//    //            DebugLog(@"shouldchangeedit %d_%d",indexPath.section,indexPath.row);
//    NSDictionary* item_json =((NSMutableArray*)self.content_data_control[indexPath.section])[indexPath.row];
//    
//    NSString* required = [item_json valueForKey:@"required"];
//    
//    if([required isEqualToString:@"true"] && string.length==0 && (textField.text.length<=1|| textField.text==nil))
//    {
//        CALayer *layer = [cell.contentView layer];
//        //            layer.borderColor = [[UIColor redColor] CGColor];
//        //            layer.borderWidth = 1.0;
//        
//        layer.shadowColor = [UIColor redColor].CGColor;
//        layer.shadowOffset = CGSizeMake(0, 0);
//        layer.shadowOpacity = 1;
//        layer.shadowRadius = 2.0;
//    }
//    else
//    {
//        CALayer *layer = [cell.contentView layer];
//        //            layer.borderColor = [[UIColor redColor] CGColor];
//        //            layer.borderWidth = 1.0;
//        
//        layer.shadowColor = [UIColor clearColor].CGColor;
//        layer.shadowOffset = CGSizeMake(0, 0);
//        layer.shadowOpacity = 1;
//        layer.shadowRadius = 2.0;
//    }
//    
//    
//    NSString* keyboard = [item_json valueForKey:@"keyboard"];
//    if(![keyboard isEqualToString:@"number"])
//        return TRUE;
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
//
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
    
    BOOL canChange = [string isEqualToString:filtered];
//
//    
//    
//    
    return canChange;
//    return true;
}
-(void) update_newprice
{
    self.price = [self.editPrice.text doubleValue];
    
    self.discount = [self.editDiscount.text doubleValue];
    
    
    self.labelNewPrice.text = [NSString stringWithFormat:@"%.2f",self.price* (1.0-self.discount/100)];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    if(textField.tag==2)
    {
        if(textField.text.length==0)
            textField.text=@"0";
        
        if([textField.text floatValue]>100.0)
        {
//            UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @"Discount error" message:@"Discount must less than 100" delegate:nil cancelButtonTitle:@"OK" 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];
            
            
            
            [RAUtils alert_view:@"Discount must less than 100." title:@"Input Error."];
            textField.text=@"0";
        }
    }
    else
    {
        float f = [textField.text floatValue];
        textField.text=[NSString stringWithFormat:@"%.2f",f];
    }
    
    [self update_newprice];
    
//    UITableViewCell *cell = (UITableViewCell *) textField.superview.superview;
//    NSIndexPath *   indexPath = [self.editorTable indexPathForCell:cell];
//    
//    
//    NSMutableDictionary* section_json=nil;
//    
//    
//    //    DebugLog(@"endedit %d_%d",indexPath.section,indexPath.row);
//    NSMutableDictionary* item_json =[((NSMutableArray*)self.content_data_control[indexPath.section])[indexPath.row] mutableCopy];
//    
//    
//    [item_json setValue:@"true" forKey:@"dirty"];
//    [item_json setValue:textField.text forKey:@"value"];
//    section_json = [[self.content_data_download objectForKey:[NSString stringWithFormat:@"section_%ld",(long)indexPath.section ]] mutableCopy];
//    int count=0;
//    
//    count=[[section_json valueForKey:@"count"] intValue];
//    
//    for(int i=0;i<count;i++)
//    {
//        NSDictionary * olditem=[section_json objectForKey:[NSString stringWithFormat:@"item_%d",i ]];
//        if([[olditem valueForKey:@"name"] isEqualToString:[item_json valueForKey:@"name" ]])
//            [section_json setObject:item_json  forKey:[NSString stringWithFormat:@"item_%d",i ]];
//        
//        
//    }
//    
//    [self.content_data_download setObject:section_json forKey:[NSString stringWithFormat:@"section_%ld",(long)indexPath.section ]];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//
//    self.lastedit = textField;
}


@end
