ffxiv_crafting/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
#![cfg_attr(test, feature(test))]

#[cfg(test)]
extern crate test;

use std::convert::TryFrom;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};

#[cfg(feature = "serde-support")]
use serde::{
    de::{self, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};

pub mod data;

/// 代表一个玩家在作业时可以使用的一个技能的枚举。
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Actions {
    // Reserve 0 so that Option<Actions> can be initialized to 0 as a None value.
    BasicSynthesis = 1,
    BasicTouch,
    MastersMend,
    HastyTouch,
    RapidSynthesis,
    Observe,
    TricksOfTheTrade,
    WasteNot,
    Veneration,
    StandardTouch,
    GreatStrides,
    Innovation,
    FinalAppraisal,
    WasteNotII,
    ByregotsBlessing,
    PreciseTouch,
    MuscleMemory,
    CarefulSynthesis,
    Manipulation,
    PrudentTouch,
    AdvancedTouch,
    Reflect,
    PreparatoryTouch,
    Groundwork,
    DelicateSynthesis,
    IntensiveSynthesis,
    TrainedEye,
    PrudentSynthesis,
    TrainedFinesse,
    CarefulObservation,
    HeartAndSoul,
    // 7.0
    RefinedTouch,
    DaringTouch,
    QuickInnovation,
    ImmaculateMend,
    TrainedPerfection,
    // fake actions
    RapidSynthesisFail,
    HastyTouchFail,
    DaringTouchFail,
    FocusedSynthesisFail,
    FocusedTouchFail,
}

#[deprecated]
pub type Skills = Actions;

#[cfg(feature = "serde-support")]
impl Serialize for Actions {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.into())
    }
}

#[cfg(feature = "serde-support")]
impl<'de> Deserialize<'de> for Actions {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct StrVisitor;
        impl<'de> Visitor<'de> for StrVisitor {
            type Value = Actions;

            fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
                formatter.write_str("a string")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Actions::try_from(v).map_err(de::Error::custom)
            }
        }
        deserializer.deserialize_str(StrVisitor)
    }
}

impl Actions {
    fn unlock_level(&self) -> u8 {
        match self {
            Actions::BasicSynthesis => 1,
            Actions::BasicTouch => 5,
            Actions::MastersMend => 7,
            Actions::HastyTouch => 9,
            Actions::RapidSynthesis => 9,
            Actions::Observe => 13,
            Actions::TricksOfTheTrade => 13,
            Actions::WasteNot => 15,
            Actions::Veneration => 15,
            Actions::StandardTouch => 18,
            Actions::GreatStrides => 21,
            Actions::Innovation => 26,
            Actions::FinalAppraisal => 42,
            Actions::WasteNotII => 47,
            Actions::ByregotsBlessing => 50,
            Actions::PreciseTouch => 53,
            Actions::MuscleMemory => 54,
            Actions::CarefulSynthesis => 62,
            Actions::Manipulation => 65,
            Actions::PrudentTouch => 66,
            Actions::AdvancedTouch => 68,
            Actions::Reflect => 69,
            Actions::PreparatoryTouch => 71,
            Actions::Groundwork => 72,
            Actions::DelicateSynthesis => 76,
            Actions::IntensiveSynthesis => 78,
            Actions::TrainedEye => 80,
            Actions::PrudentSynthesis => 88,
            Actions::TrainedFinesse => 90,
            Actions::CarefulObservation => 55,
            Actions::HeartAndSoul => 86,
            // 7.0
            Actions::RefinedTouch => 92,
            Actions::DaringTouch => 96,
            Actions::QuickInnovation => 96,
            Actions::ImmaculateMend => 98,
            Actions::TrainedPerfection => 100,
            // fake actions
            Actions::RapidSynthesisFail => 9,
            Actions::HastyTouchFail => 9,
            Actions::DaringTouchFail => 96,
            Actions::FocusedSynthesisFail => 67,
            Actions::FocusedTouchFail => 68,
        }
    }
}

impl From<&Actions> for &str {
    fn from(sk: &Actions) -> Self {
        match sk {
            Actions::BasicSynthesis => "basic_synthesis",
            Actions::BasicTouch => "basic_touch",
            Actions::MastersMend => "masters_mend",
            Actions::HastyTouch => "hasty_touch",
            Actions::RapidSynthesis => "rapid_synthesis",
            Actions::Observe => "observe",
            Actions::TricksOfTheTrade => "tricks_of_the_trade",
            Actions::WasteNot => "waste_not",
            Actions::Veneration => "veneration",
            Actions::StandardTouch => "standard_touch",
            Actions::GreatStrides => "great_strides",
            Actions::Innovation => "innovation",
            Actions::FinalAppraisal => "final_appraisal",
            Actions::WasteNotII => "waste_not_ii",
            Actions::ByregotsBlessing => "byregot_s_blessing",
            Actions::PreciseTouch => "precise_touch",
            Actions::MuscleMemory => "muscle_memory",
            Actions::CarefulSynthesis => "careful_synthesis",
            Actions::Manipulation => "manipulation",
            Actions::PrudentTouch => "prudent_touch",
            Actions::AdvancedTouch => "advanced_touch",
            Actions::Reflect => "reflect",
            Actions::PreparatoryTouch => "preparatory_touch",
            Actions::Groundwork => "groundwork",
            Actions::DelicateSynthesis => "delicate_synthesis",
            Actions::IntensiveSynthesis => "intensive_synthesis",
            Actions::TrainedEye => "trained_eye",
            Actions::PrudentSynthesis => "prudent_synthesis",
            Actions::TrainedFinesse => "trained_finesse",
            Actions::CarefulObservation => "careful_observation",
            Actions::HeartAndSoul => "heart_and_soul",
            // 7.0
            Actions::RefinedTouch => "refined_touch",
            Actions::DaringTouch => "daring_touch",
            Actions::QuickInnovation => "quick_innovation",
            Actions::ImmaculateMend => "immaculate_mend",
            Actions::TrainedPerfection => "trained_perfection",
            // fake actions
            Actions::RapidSynthesisFail => "rapid_synthsis_fail",
            Actions::HastyTouchFail => "hasty_touch_fail",
            Actions::DaringTouchFail => "daring_touch_fail",
            Actions::FocusedSynthesisFail => "focused_synthesis_fail",
            Actions::FocusedTouchFail => "focused_touch_fail",
        }
    }
}

impl TryFrom<&str> for Actions {
    type Error = UnknownSkillErr;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(match value {
            "basic_synthesis" | "制作" => Actions::BasicSynthesis,
            "basic_touch" | "加工" => Actions::BasicTouch,
            "masters_mend" | "精修" => Actions::MastersMend,
            "hasty_touch" | "仓促" => Actions::HastyTouch,
            "rapid_synthesis" | "高速制作" => Actions::RapidSynthesis,
            "observe" | "观察" => Actions::Observe,
            "tricks_of_the_trade" | "秘诀" => Actions::TricksOfTheTrade,
            "waste_not" | "俭约" => Actions::WasteNot,
            "veneration" | "崇敬" => Actions::Veneration,
            "standard_touch" | "中级加工" => Actions::StandardTouch,
            "great_strides" | "阔步" => Actions::GreatStrides,
            "innovation" | "改革" => Actions::Innovation,
            "final_appraisal" | "最终确认" => Actions::FinalAppraisal,
            "waste_not_ii" | "长期俭约" => Actions::WasteNotII,
            "byregot_s_blessing" | "比尔格的祝福" => Actions::ByregotsBlessing,
            "precise_touch" | "集中加工" => Actions::PreciseTouch,
            "muscle_memory" | "坚信" => Actions::MuscleMemory,
            "careful_synthesis" | "模范制作" => Actions::CarefulSynthesis,
            "manipulation" | "掌握" => Actions::Manipulation,
            "prudent_touch" | "俭约加工" => Actions::PrudentTouch,
            "advanced_touch" | "上级加工" => Actions::AdvancedTouch,
            "reflect" | "闲静" => Actions::Reflect,
            "preparatory_touch" | "坯料加工" => Actions::PreparatoryTouch,
            "groundwork" | "坯料制作" => Actions::Groundwork,
            "delicate_synthesis" | "精密制作" => Actions::DelicateSynthesis,
            "intensive_synthesis" | "集中制作" => Actions::IntensiveSynthesis,
            "trained_eye" | "工匠的神速技巧" => Actions::TrainedEye,
            "prudent_synthesis" | "俭约制作" => Actions::PrudentSynthesis,
            "trained_finesse" | "工匠的神技" => Actions::TrainedFinesse,
            "careful_observation" | "设计变动" => Actions::CarefulObservation,
            "heart_and_soul" | "专心致志" => Actions::HeartAndSoul,
            // 7.0
            "refined_touch" => Actions::RefinedTouch,
            "daring_touch" => Actions::DaringTouch,
            "quick_innovation" => Actions::QuickInnovation,
            "immaculate_mend" => Actions::ImmaculateMend,
            "trained_perfection" => Actions::TrainedPerfection,
            // fake actions
            "rapid_synthesis_fail" => Actions::RapidSynthesisFail,
            "hasty_touch_fail" => Actions::HastyTouchFail,
            "daring_touch_fail" => Actions::DaringTouchFail,
            "focused_synthesis_fail" => Actions::FocusedSynthesisFail,
            "focused_touch_fail" => Actions::FocusedTouchFail,
            _ => return Err(UnknownSkillErr),
        })
    }
}

#[derive(Debug)]
pub struct UnknownSkillErr;

impl Error for UnknownSkillErr {}

impl Display for UnknownSkillErr {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "unknown skill name")
    }
}

#[cfg(feature = "serde-support")]
impl de::Error for UnknownSkillErr {
    fn custom<T: Display>(_msg: T) -> Self {
        Self
    }
}

/// 代表了当前的“制作状态”,也就是俗称的球色。
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug)]
pub enum Condition {
    /// 白:通常
    Normal,
    /// 红:高品质,加工效率1.5倍
    Good,
    /// 彩:最高品质
    Excellent,
    /// 黑:低品质
    Poor,

    /// 黄:成功率增加 25%
    Centered,
    /// 蓝:耐久消耗降低 50%, 效果可与俭约叠加
    Sturdy,
    /// 绿:CP 消耗减少 50%
    Pliant,
    /// 深蓝:作业效率1.5倍
    Malleable,
    /// 紫:技能效果持续增加两回合
    Primed,
    /// 粉:下一回合必定是红球
    GoodOmen,
}

impl From<&Condition> for &str {
    fn from(c: &Condition) -> Self {
        match c {
            Condition::Normal => "normal",
            Condition::Good => "good",
            Condition::Excellent => "excellent",
            Condition::Poor => "poor",
            Condition::Centered => "centered",
            Condition::Sturdy => "sturdy",
            Condition::Pliant => "pliant",
            Condition::Malleable => "malleable",
            Condition::Primed => "primed",
            Condition::GoodOmen => "good_omen",
        }
    }
}

impl TryFrom<&str> for Condition {
    type Error = ();

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(match value {
            "normal" => Condition::Normal,
            "good" => Condition::Good,
            "excellent" => Condition::Excellent,
            "poor" => Condition::Poor,
            "centered" => Condition::Centered,
            "sturdy" => Condition::Sturdy,
            "pliant" => Condition::Pliant,
            "malleable" => Condition::Malleable,
            "primed" => Condition::Primed,
            "good_omen" => Condition::GoodOmen,
            _ => return Err(()),
        })
    }
}

impl Condition {
    fn touch_ratio(&self) -> f32 {
        match self {
            Condition::Good => 1.5,
            Condition::Excellent => 4.0,
            Condition::Poor => 0.5,
            _ => 1.0,
        }
    }

    fn synth_ratio(&self) -> f32 {
        match self {
            Condition::Malleable => 1.5,
            _ => 1.0,
        }
    }
}

/// 玩家装备属性
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub struct Attributes {
    /// 玩家等级
    pub level: u8,
    /// 制作精度
    pub craftsmanship: i32,
    /// 加工精度
    pub control: i32,
    /// 制作力
    pub craft_points: i32,
}

/// 储存了一次制作中配方的信息。
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub struct Recipe {
    /// 配方等级
    pub rlv: i32,

    /// 制作配方所需的玩家等级
    pub job_level: u8,

    /// 难度(最大进展)
    pub difficulty: u16,

    /// 最高品质
    pub quality: u32,

    /// 耐久
    pub durability: u16,

    /// 制作状态标志位,用于表示本次制作有可能出现哪些球色。
    /// 该字段从低到高每个bit依次表示对应Condition中的状态是否会出现
    ///
    /// Example:
    /// ```rust
    /// use ffxiv_crafting::Condition;
    ///
    /// fn belong(cond_flag: i32, cond: Condition) -> bool {
    ///     cond_flag & (1 << cond as usize) != 0
    /// }
    ///
    /// let cond_flag = 15; // 15即0b00001111,表示只有可能出现白球、红球、彩球和黑球
    /// assert_eq!(belong(cond_flag, Condition::Normal), true);
    /// assert_eq!(belong(cond_flag, Condition::Good), true);
    /// assert_eq!(belong(cond_flag, Condition::Excellent), true);
    /// assert_eq!(belong(cond_flag, Condition::Poor), true);
    ///
    /// assert_eq!(belong(cond_flag, Condition::Centered), false);
    /// assert_eq!(belong(cond_flag, Condition::Sturdy), false);
    /// assert_eq!(belong(cond_flag, Condition::Pliant), false);
    /// assert_eq!(belong(cond_flag, Condition::Malleable), false);
    /// assert_eq!(belong(cond_flag, Condition::Primed), false);
    /// ```
    pub conditions_flag: u16,
}

#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub struct RecipeLevel {
    pub class_job_level: u8,
    pub stars: u8,
    pub suggested_craftsmanship: u16,
    pub difficulty: u16,
    pub quality: u32,
    pub progress_divider: u8,
    pub quality_divider: u8,
    pub progress_modifier: u8,
    pub quality_modifier: u8,
    pub durability: u16,
    pub conditions_flag: u16,
}

impl Recipe {
    pub fn new(
        rlv: i32,
        difficulty_factor: u16,
        quality_factor: u16,
        durability_factor: u16,
    ) -> Self {
        let rt = data::recipe_level_table(rlv);
        Self {
            rlv,
            job_level: rt.class_job_level,
            difficulty: (rt.difficulty as u32 * difficulty_factor as u32 / 100) as u16,
            quality: rt.quality * quality_factor as u32 / 100,
            durability: rt.durability * durability_factor / 100,
            conditions_flag: rt.conditions_flag,
        }
    }
}

/// Buffs 储存了一次制作中玩家全部buff状态信息
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Default, Debug)]
pub struct Buffs {
    /// 坚信
    pub muscle_memory: u8,
    /// 阔步
    pub great_strides: u8,
    /// 崇敬
    pub veneration: u8,
    /// 改革
    pub innovation: u8,
    /// 内静
    pub inner_quiet: u8,
    /// 最终确认
    pub final_appraisal: u8,
    /// 掌握
    pub manipulation: u8,
    /// 俭约 OR 长期俭约
    pub wast_not: u8,
    /// 匠の好機
    pub expedience: u8,
    /// 专心致志
    pub heart_and_soul: LimitedActionState,
    /// 工匠的绝技
    pub trained_perfection: LimitedActionState,
    /// 设计变动使用次数
    /// 假想buff,用于记录设计变动使用的次数
    pub careful_observation_used: u8,
    /// 禁止使用Quick改革
    pub quick_innovation_used: u8,
    /// 加工连击状态:0无,1中级加工预备,2上级加工预备
    pub touch_combo_stage: u8,
    /// 观察(注视预备)
    /// 假想buff,用于处理 观察-注释制作 OR 观察-注视加工 的连击。
    pub observed: u8,
}

#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug)]
pub enum LimitedActionState {
    Unused,
    Active,
    Used,
}

impl Default for LimitedActionState {
    fn default() -> Self {
        LimitedActionState::Unused
    }
}

fn round_down(v: f64, scale: f64) -> f64 {
    (v * scale).floor() / scale
}

impl Buffs {
    pub(crate) fn synthesis(&self, skill_e: f64) -> f64 {
        let mut e = 0.0;
        if self.muscle_memory > 0 {
            e += 1.0;
        }
        if self.veneration > 0 {
            e += 0.5;
        }
        skill_e * round_down(1.0 + e, 100.0)
    }

    pub(crate) fn apply_synthesis(&mut self) {
        if self.muscle_memory > 0 {
            self.muscle_memory = 0;
        }
    }

    pub(crate) fn touch(&self, skill_e: f64) -> f64 {
        let mut bm = 1.0;
        if self.great_strides > 0 {
            bm += 1.0;
        }
        if self.innovation > 0 {
            bm += 0.5;
        }
        let iq = 1.0 + self.inner_quiet as f64 * 0.1;
        skill_e * bm * iq
    }

    pub(crate) fn apply_touch(&mut self) {
        if self.great_strides > 0 {
            self.great_strides = 0;
        }
    }

    pub(crate) fn next(&mut self) {
        self.muscle_memory = self.muscle_memory.saturating_sub(1);
        self.great_strides = self.great_strides.saturating_sub(1);
        self.veneration = self.veneration.saturating_sub(1);
        self.innovation = self.innovation.saturating_sub(1);
        self.final_appraisal = self.final_appraisal.saturating_sub(1);
        self.manipulation = self.manipulation.saturating_sub(1);
        self.wast_not = self.wast_not.saturating_sub(1);
        self.expedience = self.expedience.saturating_sub(1);
        self.next_combo();
    }

    pub(crate) fn next_combo(&mut self) {
        self.touch_combo_stage = self.touch_combo_stage.saturating_sub(2);
        self.observed = self.observed.saturating_sub(1);
    }
}

/// Status 储存一次制作模拟所需的全部状态信息
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct Status {
    /// 玩家当前身上的buff
    pub buffs: Buffs,
    /// 玩家的装备属性
    pub attributes: Attributes,
    /// 本次制作配方
    pub recipe: Recipe,
    /// 预计算数据
    pub caches: Caches,

    /// 剩余耐久
    pub durability: u16,
    /// 剩余制作力
    pub craft_points: i32,
    /// 进展
    pub progress: u16,
    /// 品质
    pub quality: u32,

    /// 步数
    pub step: i32,
    /// 制作状态
    pub condition: Condition,
}

#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct Caches {
    /// 无buff效果下100效率的作业技能能推动的进展数值
    pub base_synth: f32,
    /// 无buff效果下100效率的加工技能能推动的品质数值
    pub base_touch: f32,
}

impl Caches {
    pub fn new(attributes: &Attributes, recipe: &Recipe, rlv: &RecipeLevel) -> Self {
        Self {
            base_synth: {
                let mut base =
                    attributes.craftsmanship as f32 * 10.0 / rlv.progress_divider as f32 + 2.0;
                if attributes.level <= recipe.job_level {
                    base *= rlv.progress_modifier as f32 * 0.01
                }
                base.floor()
            },
            base_touch: {
                let mut base = attributes.control as f32 * 10.0 / rlv.quality_divider as f32 + 35.0;
                if attributes.level <= recipe.job_level {
                    base *= rlv.quality_modifier as f32 * 0.01
                }
                base.floor()
            },
        }
    }
}

/// 技能释放错误
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub enum CastActionError {
    /// 耐久不足
    DurabilityNotEnough,
    /// 制作力不足
    CraftPointNotEnough,
    /// 制作已完成无法发动技能
    CraftingAlreadyFinished,
    /// 该技能尚未学会,玩家等级不足
    PlayerLevelTooLow,
    /// 该技能只有在“高品质”及以上的状态下才能使用
    RequireGoodOrExcellent,
    /// 该技能在俭约及长期简约状态下无法使用
    NotAllowedInWastNotBuff,
    /// 该技能仅可在首次作业时发动
    OnlyAllowedInFirstStep,
    /// 该技能仅可在首次作业且用于等级低了10级及以上的配方时发动
    LevelGapMustGreaterThanTen,
    /// 该技能只有在内静的档数大于1时才可以使用
    RequireInnerQuiet1,
    /// 该技能只有在内静的档数为10时才可以使用
    RequireInnerQuiet10,
    /// 设计变动最多使用三次
    CarefulObservationUsed3,
    /// 专心致志一次制作只能使用一次
    HeartAndSoulUsed,
    /// 注视在观察之后无法失败
    FocusNeverFailsAfterObserved,
    /// 必须在仓促成功后使用
    RequireHastyTouchSuccessed,
    /// 快速改革一次制作只能使用一次
    QuickInnovationUsed,
    /// 改革状态下无法发动快速改革
    NotAllowedInInnovationBuff,
    /// 工匠的绝技一次制作只能使用一次
    TrainedPerfectionUsed,
}

impl Display for CastActionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            CastActionError::DurabilityNotEnough => "durability not enough",
            CastActionError::CraftPointNotEnough => "craft point not enough",
            CastActionError::CraftingAlreadyFinished => "crafting already finished",
            CastActionError::PlayerLevelTooLow => "player level too low",
            CastActionError::RequireGoodOrExcellent => "require good or excellent",
            CastActionError::NotAllowedInWastNotBuff => "not allowed in wast not buff",
            CastActionError::OnlyAllowedInFirstStep => "only allowed in first step",
            CastActionError::LevelGapMustGreaterThanTen => "level gap must greater than 10",
            CastActionError::RequireInnerQuiet1 => "require at least 1 stack of inner quiet",
            CastActionError::RequireInnerQuiet10 => "require 10 stack of inner quiet",
            CastActionError::CarefulObservationUsed3 => "careful observation can only use 3 times",
            CastActionError::HeartAndSoulUsed => "heart and soul can be only used once",
            CastActionError::FocusNeverFailsAfterObserved => "focus never fails after observed",
            CastActionError::RequireHastyTouchSuccessed => "require hasty touch successed first",
            CastActionError::QuickInnovationUsed => "quick innovation can be only used once",
            CastActionError::NotAllowedInInnovationBuff => "not allowed in innovation buff",
            CastActionError::TrainedPerfectionUsed => "trained perfection can be only used once",
        })
    }
}

impl Error for CastActionError {}

impl Status {
    pub fn new(attributes: Attributes, recipe: Recipe, rlv: RecipeLevel) -> Self {
        Status {
            buffs: Buffs::default(),
            caches: Caches::new(&attributes, &recipe, &rlv),
            attributes,
            recipe,
            durability: recipe.durability,
            craft_points: attributes.craft_points,
            condition: Condition::Normal,
            progress: 0,
            quality: 0,
            step: 0,
        }
    }

    pub fn calc_durability(&self, durability: u16) -> u16 {
        let mut reduce = durability;
        if let Condition::Sturdy = self.condition {
            reduce -= reduce / 2;
        }
        if self.buffs.wast_not > 0 {
            reduce -= reduce / 2;
        }
        if let LimitedActionState::Active = self.buffs.trained_perfection {
            reduce = 0;
        }
        reduce
    }

    fn consume_durability(&mut self, durability: u16) {
        if durability == 0 {
            return;
        }
        if let LimitedActionState::Active = self.buffs.trained_perfection {
            self.buffs.trained_perfection = LimitedActionState::Used;
            return;
        }
        self.durability = self
            .durability
            .saturating_sub(self.calc_durability(durability));
    }

    pub fn calc_synthesis(&self, efficiency: f64) -> u16 {
        (self.caches.base_synth as f64
            * self.buffs.synthesis(efficiency)
            * self.condition.synth_ratio() as f64) as f32 as u16
    }

    pub fn calc_touch(&self, efficiency: f64) -> u32 {
        (self.caches.base_touch as f64
            * self.buffs.touch(efficiency)
            * self.condition.touch_ratio() as f64) as f32 as u32
    }

    fn cast_synthesis(&mut self, durability: u16, efficiency: f64) {
        self.progress += self.calc_synthesis(efficiency);
        self.consume_durability(durability);
        self.buffs.apply_synthesis();
        if self.progress >= self.recipe.difficulty {
            self.progress = self.recipe.difficulty;
            if self.buffs.final_appraisal > 0 {
                self.progress -= 1;
                self.buffs.final_appraisal = 0;
            }
        }
    }

    fn cast_touch(&mut self, durability: u16, efficiency: f64, inner_quiet_addon: i8) {
        let quality_addon = self.calc_touch(efficiency);
        self.quality = (self.quality + quality_addon).min(self.recipe.quality);
        self.consume_durability(durability);
        self.buffs.apply_touch();
        self.buffs.inner_quiet = self
            .buffs
            .inner_quiet
            .saturating_add_signed(inner_quiet_addon)
            .min(10);
    }

    pub fn new_duration_buff(&self, dt: u8) -> u8 {
        if let Condition::Primed = self.condition {
            dt + 2 + 1
        } else {
            dt + 1
        }
    }

    /// 计算当前状态指定技能消耗的CP。
    /// 考虑连击与球色
    pub fn craft_point(&self, skill: Actions) -> i32 {
        let cp: i32 = match skill {
            Actions::BasicSynthesis => 0,
            Actions::BasicTouch => 18,
            Actions::MastersMend => 88,
            Actions::HastyTouch => 0,
            Actions::RapidSynthesis => 0,
            Actions::Observe => 7,
            Actions::TricksOfTheTrade => 0,
            Actions::WasteNot => 56,
            Actions::Veneration => 18,
            Actions::StandardTouch => {
                if self.buffs.touch_combo_stage == 1 {
                    18
                } else {
                    32
                }
            }
            Actions::GreatStrides => 32,
            Actions::Innovation => 18,
            Actions::FinalAppraisal => 1,
            Actions::WasteNotII => 98,
            Actions::ByregotsBlessing => 24,
            Actions::PreciseTouch => 18,
            Actions::MuscleMemory => 6,
            Actions::CarefulSynthesis => 7,
            Actions::Manipulation => 96,
            Actions::PrudentTouch => 25,
            Actions::AdvancedTouch => {
                if self.buffs.touch_combo_stage == 2 || self.buffs.observed > 0 {
                    18
                } else {
                    46
                }
            }
            Actions::Reflect => 6,
            Actions::PreparatoryTouch => 40,
            Actions::Groundwork => 18,
            Actions::DelicateSynthesis => 32,
            Actions::IntensiveSynthesis => 6,
            Actions::TrainedEye => 250,
            Actions::PrudentSynthesis => 18,
            Actions::TrainedFinesse => 32,
            Actions::CarefulObservation => 0,
            Actions::HeartAndSoul => 0,
            // 7.0
            Actions::RefinedTouch => 24,
            Actions::DaringTouch => 0,
            Actions::ImmaculateMend => 112,
            Actions::QuickInnovation => 0,
            Actions::TrainedPerfection => 0,
            // fake actions
            Actions::RapidSynthesisFail => 0,
            Actions::HastyTouchFail => 0,
            Actions::DaringTouchFail => 0,
            Actions::FocusedSynthesisFail => 5,
            Actions::FocusedTouchFail => 18,
        };
        if let Condition::Pliant = self.condition {
            cp - cp / 2
        } else {
            cp
        }
    }

    /// 发动一次技能。
    pub fn cast_action(&mut self, action: Actions) {
        self.craft_points -= self.craft_point(action);
        match action {
            Actions::BasicSynthesis => {
                self.cast_synthesis(10, if self.attributes.level < 31 { 1.0 } else { 1.2 })
            }
            Actions::RapidSynthesis => {
                self.cast_synthesis(10, if self.attributes.level < 63 { 2.5 } else { 5.0 })
            }
            Actions::CarefulSynthesis => {
                self.cast_synthesis(10, if self.attributes.level < 82 { 1.5 } else { 1.8 })
            }
            Actions::Groundwork => {
                let mut e = if self.attributes.level < 86 { 3.0 } else { 3.6 };
                let d = self.calc_durability(20);
                if self.durability < d {
                    e *= 0.5
                };
                self.cast_synthesis(20, e)
            }
            Actions::IntensiveSynthesis => {
                self.cast_synthesis(10, 4.0);
                if !matches!(self.condition, Condition::Good | Condition::Excellent) {
                    self.buffs.heart_and_soul = LimitedActionState::Used;
                }
            }
            Actions::PrudentSynthesis => self.cast_synthesis(5, 1.8),

            Actions::DelicateSynthesis => {
                self.cast_synthesis(0, if self.attributes.level < 94 { 1.0 } else { 1.5 });
                self.cast_touch(10, 1.0, 1);
            }

            Actions::BasicTouch => {
                self.cast_touch(10, 1.0, 1);
                self.buffs.touch_combo_stage = 1 + 2;
            }
            Actions::HastyTouch => {
                self.cast_touch(10, 1.0, 1);
                self.buffs.expedience = 2;
            }
            Actions::StandardTouch => {
                if self.buffs.touch_combo_stage == 1 {
                    self.buffs.touch_combo_stage = 2 + 2;
                };
                self.cast_touch(10, 1.25, 1)
            }
            Actions::AdvancedTouch => self.cast_touch(10, 1.5, 1),
            Actions::ByregotsBlessing => {
                let e = (1.0 + self.buffs.inner_quiet as f64 * 0.2).min(3.0);
                self.cast_touch(10, e, -(self.buffs.inner_quiet as i8));
            }
            Actions::PreciseTouch => {
                self.cast_touch(10, 1.5, 2);
                if !matches!(self.condition, Condition::Good | Condition::Excellent)
                    && matches!(self.buffs.heart_and_soul, LimitedActionState::Active)
                {
                    self.buffs.heart_and_soul = LimitedActionState::Used;
                }
            }
            Actions::PrudentTouch => self.cast_touch(5, 1.0, 1),
            Actions::PreparatoryTouch => self.cast_touch(20, 2.0, 2),
            Actions::TrainedFinesse => self.cast_touch(0, 1.0, 0),
            Actions::TricksOfTheTrade => {
                self.craft_points = (self.craft_points + 20).min(self.attributes.craft_points);
                if !matches!(self.condition, Condition::Good | Condition::Excellent)
                    && matches!(self.buffs.heart_and_soul, LimitedActionState::Active)
                {
                    self.buffs.heart_and_soul = LimitedActionState::Used;
                }
            }

            Actions::MastersMend => {
                self.durability = self.recipe.durability.min(self.durability + 30);
            }
            Actions::WasteNot => {
                self.buffs.wast_not = self.new_duration_buff(4);
            }
            Actions::WasteNotII => {
                self.buffs.wast_not = self.new_duration_buff(8);
            }
            Actions::Manipulation => {
                self.buffs.manipulation = self.new_duration_buff(8);
                self.buffs.next();
                self.step += 1;
                return;
            }
            Actions::MuscleMemory => {
                self.cast_synthesis(10, 3.0);
                self.buffs.muscle_memory = self.new_duration_buff(5);
            }
            Actions::Reflect => {
                self.cast_touch(10, 3.0, 2);
            }
            Actions::TrainedEye => {
                self.quality += self.recipe.quality;
            }
            Actions::Veneration => {
                self.buffs.veneration = self.new_duration_buff(4);
            }
            Actions::GreatStrides => {
                self.buffs.great_strides = self.new_duration_buff(3);
            }
            Actions::Innovation => {
                self.buffs.innovation = self.new_duration_buff(4);
            }
            Actions::Observe => {
                self.buffs.observed = 2;
            }
            Actions::FinalAppraisal => {
                self.buffs.final_appraisal = 5;
                self.buffs.next_combo();
                return;
            }
            Actions::CarefulObservation => {
                self.buffs.careful_observation_used += 1;
                self.buffs.next_combo();
                return;
            }
            Actions::HeartAndSoul => {
                self.buffs.heart_and_soul = LimitedActionState::Active;
                self.buffs.next_combo();
                return;
            }
            // 7.0
            Actions::RefinedTouch => {
                self.cast_touch(
                    10,
                    1.0,
                    if self.buffs.touch_combo_stage == 1 {
                        2
                    } else {
                        1
                    },
                );
            }
            Actions::DaringTouch => self.cast_touch(10, 1.5, 1),
            Actions::QuickInnovation => {
                if self.buffs.innovation < 1 {
                    self.buffs.innovation = 1;
                }
                self.buffs.quick_innovation_used += 1;
                self.buffs.next_combo();
                return;
            }
            Actions::ImmaculateMend => {
                self.durability = self.recipe.durability;
            }
            Actions::TrainedPerfection => {
                self.buffs.trained_perfection = LimitedActionState::Active;
            }
            // fake actions
            Actions::RapidSynthesisFail => self.consume_durability(10),
            Actions::HastyTouchFail => self.consume_durability(10),
            Actions::DaringTouchFail => self.consume_durability(10),
            Actions::FocusedSynthesisFail => self.consume_durability(10),
            Actions::FocusedTouchFail => self.consume_durability(10),
        }
        if self.buffs.manipulation > 0 && self.durability > 0 {
            self.durability += 5;
            self.durability = self.durability.min(self.recipe.durability);
        }
        self.buffs.next();
        self.step += 1;
    }

    /// 计算当前状态下某技能的成功概率,返回结果介于[0..=100]之间。
    pub fn success_rate(&self, action: Actions) -> u8 {
        let addon = match self.condition {
            Condition::Centered => 25,
            _ => 0,
        };
        addon
            + match action {
                Actions::HastyTouch | Actions::DaringTouch => 60,
                Actions::RapidSynthesis => 50,
                _ => return 100,
            }
    }

    /// 当前状态是否允许发动某技能。
    pub fn is_action_allowed(&self, action: Actions) -> Result<(), CastActionError> {
        use CastActionError::{
            CarefulObservationUsed3, CraftPointNotEnough, CraftingAlreadyFinished,
            DurabilityNotEnough, FocusNeverFailsAfterObserved, HeartAndSoulUsed,
            LevelGapMustGreaterThanTen, NotAllowedInInnovationBuff, NotAllowedInWastNotBuff,
            OnlyAllowedInFirstStep, PlayerLevelTooLow, QuickInnovationUsed, RequireGoodOrExcellent,
            RequireHastyTouchSuccessed, RequireInnerQuiet1, RequireInnerQuiet10,
            TrainedPerfectionUsed,
        };

        match action {
            _ if action.unlock_level() > self.attributes.level => Err(PlayerLevelTooLow),

            Actions::TricksOfTheTrade | Actions::IntensiveSynthesis | Actions::PreciseTouch
                if !matches!(self.condition, Condition::Good | Condition::Excellent)
                    && !matches!(self.buffs.heart_and_soul, LimitedActionState::Active) =>
            {
                Err(RequireGoodOrExcellent)
            }

            Actions::PrudentTouch | Actions::PrudentSynthesis if self.buffs.wast_not > 0 => {
                Err(NotAllowedInWastNotBuff)
            }

            Actions::MuscleMemory | Actions::Reflect | Actions::TrainedEye if self.step != 0 => {
                Err(OnlyAllowedInFirstStep)
            }

            Actions::TrainedEye if self.attributes.level < 10 + self.recipe.job_level => {
                Err(LevelGapMustGreaterThanTen)
            }

            Actions::ByregotsBlessing if self.buffs.inner_quiet < 1 => Err(RequireInnerQuiet1),
            Actions::TrainedFinesse if self.buffs.inner_quiet != 10 => Err(RequireInnerQuiet10),

            Actions::CarefulObservation if self.buffs.careful_observation_used >= 3 => {
                Err(CarefulObservationUsed3)
            }
            Actions::HeartAndSoul
                if !matches!(self.buffs.heart_and_soul, LimitedActionState::Unused) =>
            {
                Err(HeartAndSoulUsed)
            }

            Actions::FocusedSynthesisFail | Actions::FocusedTouchFail
                if self.buffs.observed > 0 =>
            {
                Err(FocusNeverFailsAfterObserved)
            }

            Actions::DaringTouch if self.buffs.expedience < 1 => Err(RequireHastyTouchSuccessed),
            Actions::QuickInnovation if self.buffs.quick_innovation_used >= 1 => {
                Err(QuickInnovationUsed)
            }
            Actions::QuickInnovation if self.buffs.innovation > 0 => {
                Err(NotAllowedInInnovationBuff)
            }
            Actions::TrainedPerfection
                if !matches!(self.buffs.trained_perfection, LimitedActionState::Unused) =>
            {
                Err(TrainedPerfectionUsed)
            }

            _ if self.durability <= 0 => Err(DurabilityNotEnough),
            _ if self.craft_point(action) > self.craft_points => Err(CraftPointNotEnough),
            _ if self.progress >= self.recipe.difficulty => Err(CraftingAlreadyFinished),
            _ => Ok(()),
        }
    }

    /// 本次制作是否已经结束。
    pub fn is_finished(&self) -> bool {
        self.progress >= self.recipe.difficulty || self.durability <= 0
    }

    /// 计算当前状态的HQ概率。
    /// 返回一个百分数,即:
    /// 如果返回89,则代表概率为89%。
    ///
    /// Calculate the HQ probability of current status.
    /// The return value is a percentage, that is,
    /// if 89 is returned, it means that the probability is 89%.
    pub fn high_quality_probability(&self) -> Option<i32> {
        let percent = self.quality * 100 / self.recipe.quality;
        data::high_quality_table(percent)
    }
}

/// 用于根据cond_flag和玩家等级计算各个球色出现概率的迭代器
///
/// Examples:
///
/// ```rust
/// use ffxiv_crafting::{Condition, ConditionIterator};
/// // 该配方的cond_flag为15,玩家等级为80。
/// for (c, p) in ConditionIterator::new(15, 80) {
///     println!("出现 {:?} 的概率为: {}", c, p);
/// }
/// ```
///
pub struct ConditionIterator {
    flag: i32,
    rate: f32,
    good_chance: f32,
    step: Option<Condition>,
}

impl ConditionIterator {
    pub fn new(flag: i32, level: i32) -> Self {
        Self {
            flag,
            rate: 0.0,
            good_chance: [0.2, 0.25][(level >= 63) as usize],
            step: Some(Condition::Normal),
        }
    }

    fn next_cond(cond: Condition) -> Option<Condition> {
        match cond {
            Condition::Normal => Some(Condition::Good),
            Condition::Good => Some(Condition::Excellent),
            Condition::Excellent => Some(Condition::Poor),
            Condition::Poor => Some(Condition::Centered),
            Condition::Centered => Some(Condition::Sturdy),
            Condition::Sturdy => Some(Condition::Pliant),
            Condition::Pliant => Some(Condition::Malleable),
            Condition::Malleable => Some(Condition::Primed),
            Condition::Primed => Some(Condition::GoodOmen),
            Condition::GoodOmen => None,
        }
    }
}

impl Iterator for ConditionIterator {
    type Item = (Condition, f32);

    fn next(&mut self) -> Option<Self::Item> {
        let cond = match self.step {
            Some(cond) => {
                let mut cond = cond;
                while self.flag & (1 << cond as i32) == 0 {
                    cond = match Self::next_cond(cond) {
                        Some(cond) => cond,
                        None => return None,
                    };
                }
                cond
            }
            None => return None,
        };
        self.step = Self::next_cond(cond);
        let expert = self.flag & (1 << Condition::Excellent as i32) == 0;
        let rate = match cond {
            Condition::Good => [self.good_chance, 0.12][expert as usize],
            Condition::Excellent => [0.04, 0.0][expert as usize],
            Condition::Poor => 0.0,
            Condition::Centered => 0.15,
            Condition::Sturdy => 0.15,
            Condition::Pliant => 0.12,
            Condition::Malleable => 0.12,
            Condition::Primed => 0.12,
            Condition::GoodOmen => 0.12,
            Condition::Normal => 1.0 - self.rate,
        };
        self.rate += rate;
        Some((cond, rate))
    }
}

#[cfg(test)]
mod tests {
    use test::Bencher;

    use crate::{data, Actions, Attributes, Condition, Recipe, Status};

    #[test]
    fn option_actions() {
        use std::mem::{size_of, transmute};
        // For Option<Actions>, the None value has to be represented by 0,
        // to achieve rapid initialization of large Actions arrays.
        assert_eq!(size_of::<Option<Actions>>(), 1);
        unsafe {
            assert_eq!(transmute::<Option<Actions>, u8>(None), 0);
        }
    }

    #[test]
    fn basic_synth() {
        let attr = Attributes {
            level: 80,
            craftsmanship: 2806,
            control: 2784,
            craft_points: 548,
        };
        let recipe = Recipe::new(517, 50, 100, 50);
        let mut s = Status::new(attr, recipe, data::recipe_level_table(recipe.rlv));

        let result = [279, 558, 837, 1000];
        for &pg in &result {
            s.cast_action(Actions::BasicSynthesis);
            assert_eq!(s.progress, pg);
        }
    }

    #[test]
    fn delicate_synth() {
        let attr = Attributes {
            level: 80,
            craftsmanship: 2762,
            control: 2794,
            craft_points: 539,
        };
        let recipe = Recipe::new(517, 100, 100, 100);
        let mut s = Status::new(attr, recipe, data::recipe_level_table(recipe.rlv));

        struct Step {
            a: Actions,
            pg: u16,
            qu: u32,
            du: u16,
            co: u8,
        }
        for (i, step) in [
            Step {
                a: Actions::DelicateSynthesis,
                pg: 230,
                qu: 301,
                du: 70,
                co: 1,
            },
            Step {
                a: Actions::DelicateSynthesis,
                pg: 460,
                qu: 632,
                du: 60,
                co: 1,
            },
            Step {
                a: Actions::DelicateSynthesis,
                pg: 690,
                qu: 993,
                du: 50,
                co: 1,
            },
            Step {
                a: Actions::DelicateSynthesis,
                pg: 920,
                qu: 1384,
                du: 40,
                co: 1,
            },
            Step {
                a: Actions::DelicateSynthesis,
                pg: 1150,
                qu: 1805,
                du: 30,
                co: 1,
            },
            Step {
                a: Actions::DelicateSynthesis,
                pg: 1380,
                qu: 2256,
                du: 20,
                co: 1,
            },
            Step {
                a: Actions::DelicateSynthesis,
                pg: 1610,
                qu: 2737,
                du: 10,
                co: 1,
            },
            Step {
                a: Actions::DelicateSynthesis,
                pg: 1840,
                qu: 3248,
                du: 0,
                co: 1,
            },
        ]
        .iter()
        .enumerate()
        {
            s.cast_action(step.a);
            assert_eq!(
                s.progress, step.pg,
                "step [{}] progress simulation fail: want {}, get {}",
                i, step.pg, s.progress
            );
            assert_eq!(
                s.quality, step.qu,
                "step [{}] quality simulation fail: want {}, get {}",
                i, step.qu, s.quality
            );
            assert_eq!(
                s.durability, step.du,
                "step [{}] durability simulation fail: want {}, get {}",
                i, step.du, s.durability
            );
            s.condition = map_cond(step.co);
        }
    }

    fn map_cond(c: u8) -> Condition {
        match c {
            1 => Condition::Normal,
            2 => Condition::Good,
            3 => Condition::Excellent,
            4 => Condition::Poor,
            5 => Condition::Centered,
            6 => Condition::Sturdy,
            7 => Condition::Pliant,
            8 => Condition::Malleable,
            9 => Condition::Primed,
            _ => unreachable!(),
        }
    }

    #[allow(unused_must_use)]
    #[bench]
    fn simple_benchmark(b: &mut Bencher) {
        let recipe = Recipe::new(580, 100, 140, 100);
        let player = Attributes {
            level: 90,
            craftsmanship: 3293,
            control: 3524,
            craft_points: 626,
        };
        let s = Status::new(player, recipe, data::recipe_level_table(recipe.rlv));
        let actions = [
            Actions::MuscleMemory,
            Actions::Manipulation,
            Actions::Veneration,
            Actions::WasteNotII,
            Actions::Groundwork,
            Actions::Groundwork,
            Actions::BasicTouch,
            Actions::Innovation,
            Actions::PreparatoryTouch,
            Actions::BasicTouch,
            Actions::StandardTouch,
            Actions::AdvancedTouch,
            Actions::Innovation,
            Actions::PrudentTouch,
            Actions::BasicTouch,
            Actions::StandardTouch,
            Actions::AdvancedTouch,
            Actions::Innovation,
            Actions::TrainedFinesse,
            Actions::TrainedFinesse,
            Actions::GreatStrides,
            Actions::ByregotsBlessing,
            Actions::CarefulSynthesis,
        ];
        b.iter(|| {
            let mut s = s.clone();
            for sk in &actions {
                s.cast_action(*sk);
            }
        })
    }

    #[test]
    fn test1() {
        let recipe = Recipe {
            rlv: 590,
            job_level: 90,
            difficulty: 4300,
            quality: 12800,
            durability: 70,
            conditions_flag: 15,
        };
        let player = Attributes {
            level: 90,
            craftsmanship: 3258,
            control: 3340,
            craft_points: 654,
        };
        let mut s = Status::new(player, recipe, data::recipe_level_table(recipe.rlv));
        let actions = vec![
            Actions::MuscleMemory,
            Actions::Manipulation,
            Actions::Veneration,
            Actions::WasteNot,
            Actions::Groundwork,
            Actions::Groundwork,
            Actions::CarefulSynthesis,
            Actions::BasicTouch,
            Actions::StandardTouch,
            Actions::AdvancedTouch,
            Actions::Innovation,
            Actions::PrudentTouch,
            Actions::PrudentTouch,
        ];
        for &sk in &actions {
            s.cast_action(sk);
        }
        assert_eq!(s.quality, 1865);
    }

    #[test]
    fn test2() {
        let recipe = Recipe {
            rlv: 640,
            job_level: 90,
            difficulty: 6600,
            quality: 14040,
            durability: 70,
            conditions_flag: 15,
        };
        let player = Attributes {
            level: 90,
            craftsmanship: 4048,
            control: 4005,
            craft_points: 594,
        };
        let mut s = Status::new(player, recipe, data::recipe_level_table(recipe.rlv));
        s.cast_action(Actions::Veneration);
        s.cast_action(Actions::Groundwork);
        assert_eq!(s.progress, 1350);
    }
}